velmen commited on
Commit
e9862cd
·
verified ·
1 Parent(s): 7fa47e0

Chess Challenge submission by velmen

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 +272 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +81 -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
+ # velmen-chess-model_v3
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [velmen](https://huggingface.co/velmen)
17
+ - **Parameters**: 992,216
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 79
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 6
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": 356,
15
+ "n_layer": 6,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.6",
19
+ "vocab_size": 79
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c9c4e154d997da71131adf2b797d7e24f4f3d923a23f963dc38c1c34b9cebe9
3
+ size 3975312
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,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer V3 for the Chess Challenge.
3
+
4
+ Enhanced version with additional chess-specific tokens for:
5
+ - Castling moves (O-O, O-O-O)
6
+ - Check/checkmate indicators (+, #)
7
+ - Capture indicator (x)
8
+ - Turn indicators ([WHITE], [BLACK])
9
+
10
+ This provides richer context while keeping vocabulary minimal (81 tokens total).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Dict, List, Optional
19
+ import re
20
+
21
+ from transformers import PreTrainedTokenizer
22
+
23
+
24
+ class ChessTokenizer(PreTrainedTokenizer):
25
+ """
26
+ Enhanced chess tokenizer with special chess notation tokens.
27
+
28
+ Vocabulary (79 tokens):
29
+ - 4 special tokens: [PAD], [BOS], [EOS], [UNK]
30
+ - 64 square tokens: a1-h8
31
+ - 4 promotion tokens: q, r, b, n
32
+ - 2 castling tokens: O-O, O-O-O
33
+ - 3 modifier tokens: +, #, x (check, checkmate, capture)
34
+ - 2 turn tokens: [WHITE], [BLACK]
35
+ """
36
+
37
+ model_input_names = ["input_ids", "attention_mask"]
38
+ vocab_files_names = {"vocab_file": "vocab.json"}
39
+
40
+ # Special tokens
41
+ PAD_TOKEN = "[PAD]"
42
+ BOS_TOKEN = "[BOS]"
43
+ EOS_TOKEN = "[EOS]"
44
+ UNK_TOKEN = "[UNK]"
45
+ WHITE_TOKEN = "[WHITE]"
46
+ BLACK_TOKEN = "[BLACK]"
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file: Optional[str] = None,
51
+ vocab: Optional[Dict[str, int]] = None,
52
+ **kwargs,
53
+ ):
54
+ self._pad_token = self.PAD_TOKEN
55
+ self._bos_token = self.BOS_TOKEN
56
+ self._eos_token = self.EOS_TOKEN
57
+ self._unk_token = self.UNK_TOKEN
58
+
59
+ kwargs.pop("pad_token", None)
60
+ kwargs.pop("bos_token", None)
61
+ kwargs.pop("eos_token", None)
62
+ kwargs.pop("unk_token", None)
63
+
64
+ # Enhanced regex pattern for chess notation
65
+ # Matches: squares, promotions, castling, modifiers, turn indicators
66
+ self.token_pattern = re.compile(
67
+ r'O-O-O|O-O|' # Castling (match O-O-O first!)
68
+ r'\[WHITE\]|\[BLACK\]|' # Turn indicators
69
+ r'[a-h][1-8]|' # Squares
70
+ r'[qrbn]|' # Promotions
71
+ r'[+#x]' # Check, checkmate, capture
72
+ )
73
+
74
+ if vocab is not None:
75
+ self._vocab = vocab
76
+ elif vocab_file is not None and os.path.exists(vocab_file):
77
+ with open(vocab_file, "r", encoding="utf-8") as f:
78
+ self._vocab = json.load(f)
79
+ else:
80
+ self._vocab = self._create_default_vocab()
81
+
82
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
83
+
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 the complete vocabulary with all chess-specific tokens.
95
+
96
+ Total: 79 tokens
97
+ """
98
+ vocab = {}
99
+ idx = 0
100
+
101
+ # Special tokens (0-3)
102
+ for token in [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]:
103
+ vocab[token] = idx
104
+ idx += 1
105
+
106
+ # Squares (4-67)
107
+ for f in 'abcdefgh':
108
+ for r in '12345678':
109
+ vocab[f"{f}{r}"] = idx
110
+ idx += 1
111
+
112
+ # Promotions (68-71)
113
+ for p in ['q', 'r', 'b', 'n']:
114
+ vocab[p] = idx
115
+ idx += 1
116
+
117
+ # Castling (72-73)
118
+ vocab["O-O"] = idx
119
+ idx += 1
120
+ vocab["O-O-O"] = idx
121
+ idx += 1
122
+
123
+ # Modifiers (74-76)
124
+ vocab["+"] = idx # Check
125
+ idx += 1
126
+ vocab["#"] = idx # Checkmate
127
+ idx += 1
128
+ vocab["x"] = idx # Capture
129
+ idx += 1
130
+
131
+ # Turn indicators (77-78)
132
+ vocab[self.WHITE_TOKEN] = idx
133
+ idx += 1
134
+ vocab[self.BLACK_TOKEN] = idx
135
+ idx += 1
136
+
137
+ return vocab
138
+
139
+ def _tokenize(self, text: str) -> List[str]:
140
+ """
141
+ Enhanced tokenization with preprocessing for common chess notation variants.
142
+
143
+ Handles:
144
+ - Lichess format: (Q) → q, (x) → x, (+) → +, (#) → #
145
+ - Standard notation: keeps O-O, O-O-O, +, #, x as-is
146
+ - Extracts squares, promotions, castling, and modifiers
147
+ """
148
+ # Normalize Lichess-style parentheses notation
149
+ text = (text.replace("(Q)", "q")
150
+ .replace("(R)", "r")
151
+ .replace("(B)", "b")
152
+ .replace("(N)", "n")
153
+ .replace("(x)", "x")
154
+ .replace("(+)", "+")
155
+ .replace("(#)", "#")
156
+ .replace("(+*)", "#") # Checkmate variant
157
+ .replace("(o)", "O-O") # Kingside castling
158
+ .replace("(O)", "O-O-O")) # Queenside castling
159
+
160
+ # Extract all chess tokens
161
+ return self.token_pattern.findall(text)
162
+
163
+ def _convert_token_to_id(self, token: str) -> int:
164
+ """Convert a token to its ID."""
165
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
166
+
167
+ def _convert_id_to_token(self, index: int) -> str:
168
+ """Convert an ID to its token."""
169
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
170
+
171
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
172
+ """
173
+ Reconstructs chess moves in standard UCI format with modifiers.
174
+
175
+ Intelligently groups tokens:
176
+ - Combines squares into moves: e2, e4 → e2e4
177
+ - Attaches promotions: a7, a8, q → a7a8q
178
+ - Keeps modifiers separate: e2e4, x, + → e2e4x+
179
+ - Preserves castling and turn indicators
180
+ """
181
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
182
+ clean_tokens = [t for t in tokens if t not in special]
183
+
184
+ output = []
185
+ modifiers = {'+', '#', 'x'}
186
+ promotions = {'q', 'r', 'b', 'n'}
187
+
188
+ for token in clean_tokens:
189
+ # Castling and turn indicators stay as-is
190
+ if token in ["O-O", "O-O-O", self.WHITE_TOKEN, self.BLACK_TOKEN]:
191
+ output.append(token)
192
+ # Promotions attach to previous move
193
+ elif token in promotions and output and len(output[-1]) == 4:
194
+ output[-1] += token
195
+ # Modifiers can attach or stay separate (flexible)
196
+ elif token in modifiers and output:
197
+ output[-1] += token
198
+ # Square: either start new move or complete previous
199
+ elif len(token) == 2 and token[0] in 'abcdefgh':
200
+ if output and len(output[-1]) == 2 and output[-1][0] in 'abcdefgh':
201
+ # Complete the move
202
+ output[-1] += token
203
+ else:
204
+ # Start new move
205
+ output.append(token)
206
+ else:
207
+ output.append(token)
208
+
209
+ return " ".join(output)
210
+
211
+ def add_turn_indicators(self, text: str, add_white_indicator: bool = True) -> str:
212
+ """
213
+ Add turn indicators to help the model understand whose turn it is.
214
+
215
+ Args:
216
+ text: Game string (space-separated moves)
217
+ add_white_indicator: If True, add [WHITE] at start (white moves first)
218
+
219
+ Returns:
220
+ Game string with turn indicators
221
+ """
222
+ moves = text.strip().split()
223
+ result = []
224
+
225
+ # White starts (by convention)
226
+ is_white = add_white_indicator
227
+
228
+ for move in moves:
229
+ turn_token = self.WHITE_TOKEN if is_white else self.BLACK_TOKEN
230
+ result.append(turn_token)
231
+ result.append(move)
232
+ is_white = not is_white
233
+
234
+ return " ".join(result)
235
+
236
+ def save_vocabulary(
237
+ self,
238
+ save_directory: str,
239
+ filename_prefix: Optional[str] = None,
240
+ ) -> tuple:
241
+ """Save the vocabulary to a JSON file."""
242
+ if not os.path.isdir(save_directory):
243
+ os.makedirs(save_directory, exist_ok=True)
244
+
245
+ vocab_file = os.path.join(
246
+ save_directory,
247
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
248
+ )
249
+
250
+ with open(vocab_file, "w", encoding="utf-8") as f:
251
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
252
+
253
+ return (vocab_file,)
254
+
255
+ @classmethod
256
+ def build_vocab_from_iterator(cls, iterator, min_frequency=1):
257
+ """Returns tokenizer with fixed vocabulary (doesn't depend on data)."""
258
+ return cls()
259
+
260
+ @classmethod
261
+ def build_vocab_from_dataset(cls, **kwargs):
262
+ """Returns tokenizer with fixed vocabulary (doesn't depend on data)."""
263
+ return cls()
264
+
265
+ @property
266
+ def vocab_size(self) -> int:
267
+ """Return the size of the vocabulary (79 tokens)."""
268
+ return len(self._vocab)
269
+
270
+ def get_vocab(self) -> Dict[str, int]:
271
+ """Return the vocabulary as a dictionary."""
272
+ return dict(self._vocab)
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,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "a1": 4,
7
+ "a2": 5,
8
+ "a3": 6,
9
+ "a4": 7,
10
+ "a5": 8,
11
+ "a6": 9,
12
+ "a7": 10,
13
+ "a8": 11,
14
+ "b1": 12,
15
+ "b2": 13,
16
+ "b3": 14,
17
+ "b4": 15,
18
+ "b5": 16,
19
+ "b6": 17,
20
+ "b7": 18,
21
+ "b8": 19,
22
+ "c1": 20,
23
+ "c2": 21,
24
+ "c3": 22,
25
+ "c4": 23,
26
+ "c5": 24,
27
+ "c6": 25,
28
+ "c7": 26,
29
+ "c8": 27,
30
+ "d1": 28,
31
+ "d2": 29,
32
+ "d3": 30,
33
+ "d4": 31,
34
+ "d5": 32,
35
+ "d6": 33,
36
+ "d7": 34,
37
+ "d8": 35,
38
+ "e1": 36,
39
+ "e2": 37,
40
+ "e3": 38,
41
+ "e4": 39,
42
+ "e5": 40,
43
+ "e6": 41,
44
+ "e7": 42,
45
+ "e8": 43,
46
+ "f1": 44,
47
+ "f2": 45,
48
+ "f3": 46,
49
+ "f4": 47,
50
+ "f5": 48,
51
+ "f6": 49,
52
+ "f7": 50,
53
+ "f8": 51,
54
+ "g1": 52,
55
+ "g2": 53,
56
+ "g3": 54,
57
+ "g4": 55,
58
+ "g5": 56,
59
+ "g6": 57,
60
+ "g7": 58,
61
+ "g8": 59,
62
+ "h1": 60,
63
+ "h2": 61,
64
+ "h3": 62,
65
+ "h4": 63,
66
+ "h5": 64,
67
+ "h6": 65,
68
+ "h7": 66,
69
+ "h8": 67,
70
+ "q": 68,
71
+ "r": 69,
72
+ "b": 70,
73
+ "n": 71,
74
+ "O-O": 72,
75
+ "O-O-O": 73,
76
+ "+": 74,
77
+ "#": 75,
78
+ "x": 76,
79
+ "[WHITE]": 77,
80
+ "[BLACK]": 78
81
+ }