matheoqtb commited on
Commit
6a85e7b
·
verified ·
1 Parent(s): 9801d91

Chess Challenge submission by matheoqtb

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 +226 -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
+ # chess-model-qtb-v2
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [matheoqtb](https://huggingface.co/matheoqtb)
17
+ - **Parameters**: 970,112
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 76
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 7
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": 256,
15
+ "n_layer": 7,
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:52798539a84c71a108bff0c1889c6f4160dffe4349de3385e590980bb1b8b733
3
+ size 3887912
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,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ This tokenizer treats chess moves using a 'Square-Aware' Character strategy.
5
+ Instead of full moves (e.g., WPe2e4), it splits them into meaningful atomic parts:
6
+ - Pieces/Colors: W, B, P, N, B, R, Q, K
7
+ - Full Squares: e2, e4, h8 (keeps coordinates together for geometric understanding)
8
+ - Separators: Space " "
9
+
10
+ Example: "WPe2e4" -> ["W", "P", "e2", "e4"]
11
+ """
12
+
13
+ from __future__ import annotations
14
+ import re
15
+ import json
16
+ import os
17
+ from typing import Dict, List, Optional
18
+ from transformers import PreTrainedTokenizer
19
+
20
+ class ChessTokenizer(PreTrainedTokenizer):
21
+ """
22
+ A custom tokenizer for chess moves using 'Square-Aware' tokenization.
23
+
24
+ It maps atomic chess components (squares like 'e4', pieces like 'P') to IDs.
25
+ This creates a small, dense vocabulary (~80 tokens) allowing deeper models.
26
+ """
27
+
28
+ model_input_names = ["input_ids", "attention_mask"]
29
+ vocab_files_names = {"vocab_file": "vocab.json"}
30
+
31
+ # Special tokens
32
+ PAD_TOKEN = "[PAD]"
33
+ BOS_TOKEN = "[BOS]"
34
+ EOS_TOKEN = "[EOS]"
35
+ UNK_TOKEN = "[UNK]"
36
+
37
+ def __init__(
38
+ self,
39
+ vocab_file: Optional[str] = None,
40
+ vocab: Optional[Dict[str, int]] = None,
41
+ **kwargs,
42
+ ):
43
+ # Initialize special tokens
44
+ self._pad_token = self.PAD_TOKEN
45
+ self._bos_token = self.BOS_TOKEN
46
+ self._eos_token = self.EOS_TOKEN
47
+ self._unk_token = self.UNK_TOKEN
48
+
49
+ # Clean kwargs to avoid conflicts
50
+ kwargs.pop("pad_token", None)
51
+ kwargs.pop("bos_token", None)
52
+ kwargs.pop("eos_token", None)
53
+ kwargs.pop("unk_token", None)
54
+
55
+ # Load or create vocabulary
56
+ if vocab is not None:
57
+ self._vocab = vocab
58
+ elif vocab_file is not None and os.path.exists(vocab_file):
59
+ with open(vocab_file, "r", encoding="utf-8") as f:
60
+ self._vocab = json.load(f)
61
+ else:
62
+ # Minimal default vocab (placeholder)
63
+ self._vocab = self._create_default_vocab()
64
+
65
+ # Create reverse mapping (ID -> Token)
66
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
67
+
68
+ super().__init__(
69
+ pad_token=self._pad_token,
70
+ bos_token=self._bos_token,
71
+ eos_token=self._eos_token,
72
+ unk_token=self._unk_token,
73
+ **kwargs,
74
+ )
75
+
76
+ def _create_default_vocab(self) -> Dict[str, int]:
77
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
78
+ return {token: idx for idx, token in enumerate(special_tokens)}
79
+
80
+ @classmethod
81
+ def build_vocab_from_iterator(
82
+ cls,
83
+ iterator,
84
+ min_frequency: int = 1,
85
+ ) -> "ChessTokenizer":
86
+ """
87
+ Build vocabulary by scanning the dataset.
88
+ Splits text into pieces (W, P) and full squares (e2, e4).
89
+ """
90
+ from collections import Counter
91
+ token_counts = Counter()
92
+
93
+ for game in iterator:
94
+ # 1. Nettoyage : on enlève les suffixes (x), (+)
95
+ game = re.sub(r'\(.*?\)', '', game)
96
+
97
+ # 2. Découpage par coups pour gérer les espaces correctement
98
+ moves = game.strip().split()
99
+
100
+ for i, move in enumerate(moves):
101
+ # Regex : Capture soit une case [a-h][1-8], soit n'importe quel autre char (.)
102
+ tokens = re.findall(r'[a-h][1-8]|.', move)
103
+ token_counts.update(tokens)
104
+
105
+ # Ajout explicite de l'espace entre les coups (sauf après le dernier)
106
+ if i < len(moves) - 1:
107
+ token_counts.update([" "])
108
+
109
+ # Filter and sort tokens
110
+ tokens = [t for t, count in token_counts.items() if count >= min_frequency]
111
+ tokens = sorted(tokens)
112
+
113
+ # Build final vocabulary dict
114
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
115
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
116
+
117
+ return cls(vocab=vocab)
118
+
119
+ @classmethod
120
+ def build_vocab_from_dataset(
121
+ cls,
122
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
123
+ split: str = "train",
124
+ column: str = "text",
125
+ min_frequency: int = 1, # Keep at 1 to catch all squares/pieces
126
+ max_samples: Optional[int] = 50000,
127
+ ) -> "ChessTokenizer":
128
+ from datasets import load_dataset
129
+ dataset = load_dataset(dataset_name, split=split)
130
+
131
+ if max_samples is not None:
132
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
133
+
134
+ def game_iterator():
135
+ for example in dataset:
136
+ yield example[column]
137
+
138
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
139
+
140
+ @property
141
+ def vocab_size(self) -> int:
142
+ return len(self._vocab)
143
+
144
+ def get_vocab(self) -> Dict[str, int]:
145
+ return dict(self._vocab)
146
+
147
+ def _tokenize(self, text: str) -> List[str]:
148
+ """
149
+ Tokenize input text using the Square-Aware logic.
150
+ "WPe2e4" -> ["W", "P", "e2", "e4"]
151
+ """
152
+ # 1. Remove suffixes
153
+ text = re.sub(r'\(.*?\)', '', text)
154
+
155
+ # 2. Split into moves to manage spaces
156
+ moves = text.strip().split()
157
+
158
+ all_tokens = []
159
+ for i, move in enumerate(moves):
160
+ # Regex match: squares OR single chars
161
+ tokens = re.findall(r'[a-h][1-8]|.', move)
162
+ all_tokens.extend(tokens)
163
+
164
+ # Re-insert space token between moves
165
+ if i < len(moves) - 1:
166
+ all_tokens.append(" ")
167
+
168
+ return all_tokens
169
+
170
+ def _convert_token_to_id(self, token: str) -> int:
171
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
172
+
173
+ def _convert_id_to_token(self, index: int) -> str:
174
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
175
+
176
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
177
+ """
178
+ Convert tokens back to string.
179
+ IMPORTANT: Join with empty string "" because space " " is already a token.
180
+ """
181
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
182
+ filtered_tokens = [t for t in tokens if t not in special]
183
+
184
+ # Join with "" because the space character is treated as a token in our vocab
185
+ return "".join(filtered_tokens)
186
+
187
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
188
+ if not os.path.isdir(save_directory):
189
+ os.makedirs(save_directory, exist_ok=True)
190
+
191
+ vocab_file = os.path.join(
192
+ save_directory,
193
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
194
+ )
195
+
196
+ with open(vocab_file, "w", encoding="utf-8") as f:
197
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
198
+
199
+ return (vocab_file,)
200
+
201
+ def count_vocab_from_dataset(
202
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
203
+ split: str = "train",
204
+ column: str = "text",
205
+ max_samples: Optional[int] = 10000,
206
+ ) -> Dict[str, int]:
207
+ # Utility function remains similar but should use the new regex logic if needed for analysis
208
+ # For simple counting, split() is often enough approximation, but let's be precise:
209
+ from collections import Counter
210
+ from datasets import load_dataset
211
+ import re
212
+
213
+ dataset = load_dataset(dataset_name, split=split)
214
+ if max_samples is not None:
215
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
216
+
217
+ token_counts = Counter()
218
+ for example in dataset:
219
+ text = re.sub(r'\(.*?\)', '', example[column])
220
+ moves = text.strip().split()
221
+ for move in moves:
222
+ tokens = re.findall(r'[a-h][1-8]|.', move)
223
+ token_counts.update(tokens)
224
+ token_counts.update([" "])
225
+
226
+ 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
+ }