Sammy972 commited on
Commit
e88e3ab
·
verified ·
1 Parent(s): 63f8755

Chess Challenge submission by Sammy972

Browse files
Files changed (7) hide show
  1. README.md +26 -0
  2. config.json +21 -0
  3. model.safetensors +3 -0
  4. special_tokens_map.json +6 -0
  5. tokenizer.py +261 -0
  6. tokenizer_config.json +49 -0
  7. vocab.json +87 -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-sam
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Sammy972](https://huggingface.co/Sammy972)
17
+ - **Parameters**: 952,224
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 85
24
+ - **Embedding dim**: 96
25
+ - **Layers**: 8
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "output/final_model",
3
+ "architectures": [
4
+ "ChessForCausalLM"
5
+ ],
6
+ "bos_token_id": 1,
7
+ "dropout": 0.1,
8
+ "eos_token_id": 2,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "model_type": "chess_transformer",
11
+ "n_ctx": 512,
12
+ "n_embd": 96,
13
+ "n_head": 4,
14
+ "n_inner": 384,
15
+ "n_layer": 8,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "torch_dtype": "float32",
19
+ "transformers_version": "4.46.3",
20
+ "vocab_size": 85
21
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12b6170fa69d1033fe9b7f80029916d8bf495340311a739fd6c21a5954079e10
3
+ size 3817288
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,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =========================
2
+ # CELLULE 1 — src/tokenizer.py
3
+ # ➜ Remplace TOUT le contenu du fichier par ce code
4
+ # =========================
5
+
6
+ """
7
+ Factorized Chess Tokenizer for the Chess Challenge.
8
+
9
+ Instead of "1 move = 1 token", we represent a move as multiple tokens:
10
+ - Side: [W] / [B]
11
+ - Piece: [P], [N], [BISHOP], [R], [Q], [K]
12
+ - Squares: [e2], [e4], ...
13
+ - Optional suffix: [x], [+], [#], [O-O], [O-O-O]
14
+ - Optional promotion: [prom_Q], [prom_R], [prom_B], [prom_N]
15
+
16
+ Important:
17
+ - We KEEP squares as tokens so evaluation (regex [a-h][1-8]) can extract UCI moves.
18
+ - We decode squares to plain "e2" etc, and promotions to "q/r/b/n" so evaluate.py can detect promotions.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import re
26
+ from typing import Dict, List, Optional
27
+
28
+ from transformers import PreTrainedTokenizer
29
+
30
+
31
+ MOVE_RE = re.compile(
32
+ r"^(?P<side>[WB])"
33
+ r"(?P<piece>[PNBRQK])"
34
+ r"(?P<src>[a-h][1-8])"
35
+ r"(?P<dst>[a-h][1-8])"
36
+ r"(?P<suffix>.*)$"
37
+ )
38
+
39
+ SQUARE_TOKEN_RE = re.compile(r"^\[[a-h][1-8]\]$")
40
+
41
+
42
+
43
+ class ChessTokenizer(PreTrainedTokenizer):
44
+ model_input_names = ["input_ids", "attention_mask"]
45
+ vocab_files_names = {"vocab_file": "vocab.json"}
46
+
47
+ PAD_TOKEN = "[PAD]"
48
+ BOS_TOKEN = "[BOS]"
49
+ EOS_TOKEN = "[EOS]"
50
+ UNK_TOKEN = "[UNK]"
51
+
52
+ def __init__(
53
+ self,
54
+ vocab_file: Optional[str] = None,
55
+ vocab: Optional[Dict[str, int]] = None,
56
+ **kwargs,
57
+ ):
58
+ # Special tokens
59
+ self._pad_token = self.PAD_TOKEN
60
+ self._bos_token = self.BOS_TOKEN
61
+ self._eos_token = self.EOS_TOKEN
62
+ self._unk_token = self.UNK_TOKEN
63
+
64
+ # Avoid duplicate kwargs
65
+ kwargs.pop("pad_token", None)
66
+ kwargs.pop("bos_token", None)
67
+ kwargs.pop("eos_token", None)
68
+ kwargs.pop("unk_token", None)
69
+
70
+ if vocab is not None:
71
+ self._vocab = vocab
72
+ elif vocab_file is not None and os.path.exists(vocab_file):
73
+ with open(vocab_file, "r", encoding="utf-8") as f:
74
+ self._vocab = json.load(f)
75
+ else:
76
+ self._vocab = self._create_default_vocab()
77
+
78
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
79
+
80
+ super().__init__(
81
+ pad_token=self._pad_token,
82
+ bos_token=self._bos_token,
83
+ eos_token=self._eos_token,
84
+ unk_token=self._unk_token,
85
+ **kwargs,
86
+ )
87
+
88
+ def _create_default_vocab(self) -> Dict[str, int]:
89
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
90
+
91
+ side_tokens = ["[W]", "[B]"]
92
+ piece_tokens = ["[P]", "[N]", "[BISHOP]", "[R]", "[Q]", "[K]"]
93
+
94
+ square_tokens = [f"[{file}{rank}]" for rank in "12345678" for file in "abcdefgh"]
95
+
96
+ suffix_tokens = [
97
+ "[x]", "[+]", "[#]",
98
+ "[O-O]", "[O-O-O]",
99
+ "[prom_Q]", "[prom_R]", "[prom_B]", "[prom_N]",
100
+ ]
101
+
102
+ vocab_list = special_tokens + side_tokens + piece_tokens + square_tokens + suffix_tokens
103
+ return {tok: i for i, tok in enumerate(vocab_list)}
104
+
105
+ # IMPORTANT: prevent HF from auto-adding BOS/EOS on top of your text
106
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
107
+ if token_ids_1 is None:
108
+ return token_ids_0
109
+ return token_ids_0 + token_ids_1
110
+
111
+ @classmethod
112
+ def build_vocab_from_iterator(cls, iterator, min_frequency: int = 1) -> "ChessTokenizer":
113
+ # Fixed vocab (we ignore dataset frequency)
114
+ return cls()
115
+
116
+ @classmethod
117
+ def build_vocab_from_dataset(
118
+ cls,
119
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
120
+ split: str = "train",
121
+ column: str = "text",
122
+ min_frequency: int = 500,
123
+ max_samples: Optional[int] = 100000,
124
+ ) -> "ChessTokenizer":
125
+ # Fixed vocab (we ignore dataset frequency)
126
+ return cls()
127
+
128
+ @property
129
+ def vocab_size(self) -> int:
130
+ return len(self._vocab)
131
+
132
+ def get_vocab(self) -> Dict[str, int]:
133
+ return dict(self._vocab)
134
+
135
+ def _tokenize(self, text: str) -> List[str]:
136
+ tokens: List[str] = []
137
+ parts = str(text).strip().split()
138
+
139
+ specials = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
140
+
141
+ for p in parts:
142
+ if p in specials:
143
+ tokens.append(p)
144
+ continue
145
+
146
+ m = MOVE_RE.match(p)
147
+ if not m:
148
+ tokens.append(self.UNK_TOKEN)
149
+ continue
150
+
151
+ side = m.group("side")
152
+ piece = m.group("piece")
153
+ src = m.group("src")
154
+ dst = m.group("dst")
155
+ suffix = m.group("suffix") or ""
156
+
157
+ tokens.append("[W]" if side == "W" else "[B]")
158
+
159
+ if piece == "B":
160
+ tokens.append("[BISHOP]")
161
+ else:
162
+ tokens.append(f"[{piece}]")
163
+
164
+ tokens.append(f"[{src}]")
165
+ tokens.append(f"[{dst}]")
166
+
167
+ # capture/check/checkmate
168
+ if "x" in suffix:
169
+ tokens.append("[x]")
170
+ if "*" in suffix:
171
+ tokens.append("[#]")
172
+ elif "+" in suffix:
173
+ tokens.append("[+]")
174
+
175
+ # castling annotation (optional, squares already encode it)
176
+ if piece == "K":
177
+ if (src, dst) in (("e1", "g1"), ("e8", "g8")) or "(o)" in suffix:
178
+ tokens.append("[O-O]")
179
+ elif (src, dst) in (("e1", "c1"), ("e8", "c8")) or "(O)" in suffix:
180
+ tokens.append("[O-O-O]")
181
+
182
+ # promotion
183
+ if "=" in suffix:
184
+ i = suffix.find("=")
185
+ if i != -1 and i + 1 < len(suffix):
186
+ promo = suffix[i + 1].upper()
187
+ if promo in ("Q", "R", "B", "N"):
188
+ tokens.append(f"[prom_{promo}]")
189
+
190
+ return tokens
191
+
192
+ def _convert_token_to_id(self, token: str) -> int:
193
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 3))
194
+
195
+ def _convert_id_to_token(self, index: int) -> str:
196
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
197
+
198
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
199
+ """
200
+ Decode tokens into a compact string so evaluate.py can extract squares easily.
201
+
202
+ Examples:
203
+ [W] [P] [e2] [e4] -> "WPe2e4"
204
+ ... [e7] [e8] [prom_Q] -> "WPe7e8q" (promotion detectable)
205
+ """
206
+ out: List[str] = []
207
+ for t in tokens:
208
+ if t in (self.PAD_TOKEN,):
209
+ continue
210
+
211
+ # keep these literal so evaluator can compare EOS if needed
212
+ if t in (self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN):
213
+ out.append(t)
214
+ continue
215
+
216
+ if t == "[W]":
217
+ out.append("W")
218
+ elif t == "[B]":
219
+ out.append("B")
220
+ elif t == "[BISHOP]":
221
+ out.append("B")
222
+ elif t in ("[P]", "[N]", "[R]", "[Q]", "[K]"):
223
+ out.append(t.strip("[]"))
224
+ elif SQUARE_TOKEN_RE.match(t):
225
+ out.append(t[1:-1]) # "[e2]" -> "e2"
226
+ elif t == "[x]":
227
+ out.append("(x)")
228
+ elif t == "[+]":
229
+ out.append("(+)")
230
+ elif t == "[#]":
231
+ out.append("(+*)")
232
+ elif t == "[O-O]":
233
+ out.append("(o)")
234
+ elif t == "[O-O-O]":
235
+ out.append("(O)")
236
+ elif t == "[prom_Q]":
237
+ out.append("q")
238
+ elif t == "[prom_R]":
239
+ out.append("r")
240
+ elif t == "[prom_B]":
241
+ out.append("b")
242
+ elif t == "[prom_N]":
243
+ out.append("n")
244
+ else:
245
+ out.append(t)
246
+
247
+ return "".join(out)
248
+
249
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
250
+ if not os.path.isdir(save_directory):
251
+ os.makedirs(save_directory, exist_ok=True)
252
+
253
+ vocab_file = os.path.join(
254
+ save_directory,
255
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
256
+ )
257
+
258
+ with open(vocab_file, "w", encoding="utf-8") as f:
259
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
260
+
261
+ return (vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "model_max_length": 1000000000000000019884624838656,
46
+ "pad_token": "[PAD]",
47
+ "tokenizer_class": "ChessTokenizer",
48
+ "unk_token": "[UNK]"
49
+ }
vocab.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[W]": 4,
7
+ "[B]": 5,
8
+ "[P]": 6,
9
+ "[N]": 7,
10
+ "[BISHOP]": 8,
11
+ "[R]": 9,
12
+ "[Q]": 10,
13
+ "[K]": 11,
14
+ "[a1]": 12,
15
+ "[b1]": 13,
16
+ "[c1]": 14,
17
+ "[d1]": 15,
18
+ "[e1]": 16,
19
+ "[f1]": 17,
20
+ "[g1]": 18,
21
+ "[h1]": 19,
22
+ "[a2]": 20,
23
+ "[b2]": 21,
24
+ "[c2]": 22,
25
+ "[d2]": 23,
26
+ "[e2]": 24,
27
+ "[f2]": 25,
28
+ "[g2]": 26,
29
+ "[h2]": 27,
30
+ "[a3]": 28,
31
+ "[b3]": 29,
32
+ "[c3]": 30,
33
+ "[d3]": 31,
34
+ "[e3]": 32,
35
+ "[f3]": 33,
36
+ "[g3]": 34,
37
+ "[h3]": 35,
38
+ "[a4]": 36,
39
+ "[b4]": 37,
40
+ "[c4]": 38,
41
+ "[d4]": 39,
42
+ "[e4]": 40,
43
+ "[f4]": 41,
44
+ "[g4]": 42,
45
+ "[h4]": 43,
46
+ "[a5]": 44,
47
+ "[b5]": 45,
48
+ "[c5]": 46,
49
+ "[d5]": 47,
50
+ "[e5]": 48,
51
+ "[f5]": 49,
52
+ "[g5]": 50,
53
+ "[h5]": 51,
54
+ "[a6]": 52,
55
+ "[b6]": 53,
56
+ "[c6]": 54,
57
+ "[d6]": 55,
58
+ "[e6]": 56,
59
+ "[f6]": 57,
60
+ "[g6]": 58,
61
+ "[h6]": 59,
62
+ "[a7]": 60,
63
+ "[b7]": 61,
64
+ "[c7]": 62,
65
+ "[d7]": 63,
66
+ "[e7]": 64,
67
+ "[f7]": 65,
68
+ "[g7]": 66,
69
+ "[h7]": 67,
70
+ "[a8]": 68,
71
+ "[b8]": 69,
72
+ "[c8]": 70,
73
+ "[d8]": 71,
74
+ "[e8]": 72,
75
+ "[f8]": 73,
76
+ "[g8]": 74,
77
+ "[h8]": 75,
78
+ "[x]": 76,
79
+ "[+]": 77,
80
+ "[#]": 78,
81
+ "[O-O]": 79,
82
+ "[O-O-O]": 80,
83
+ "[prom_Q]": 81,
84
+ "[prom_R]": 82,
85
+ "[prom_B]": 83,
86
+ "[prom_N]": 84
87
+ }