filomeneroquefort commited on
Commit
30b1d19
·
verified ·
1 Parent(s): c9407a6

Chess Challenge submission by filomeneroquefort

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 +6 -0
  5. tokenizer.py +197 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +92 -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_filo_7
10
+ Chess model submitted to the LLM Course Chess Challenge.
11
+ ## Submission Info
12
+ - **Submitted by**: [filomeneroquefort](https://huggingface.co/filomeneroquefort)
13
+ - **Parameters**: 885,696
14
+ - **Organization**: LLM-course
15
+ ## Model Details
16
+ - **Architecture**: Chess Transformer (GPT-style)
17
+ - **Vocab size**: 90
18
+ - **Embedding dim**: 112
19
+ - **Layers**: 6
20
+ - **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": 1024,
12
+ "n_embd": 112,
13
+ "n_head": 8,
14
+ "n_inner": 336,
15
+ "n_layer": 6,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.6",
19
+ "vocab_size": 90
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77f947eafa7925a4f394a23f72d0b2c74bdac0e3b41516a6ea69afb532cc2d46
3
+ size 3549224
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,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Atomic Chess Tokenizer.
3
+
4
+ Decomposes chess moves into atomic components:
5
+ [Piece] + [Source] + [Destination] + [Suffix]
6
+
7
+ Example: "WPe2e4(x)" -> ["WP", "e2", "e4", "(x)"]
8
+
9
+ Benefits:
10
+ - Drastically reduces vocab size (~1200 -> ~90)
11
+ - Saves ~140k parameters in the embedding layer
12
+ - Allows the model to learn spatial relationships (e2 is close to e3)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ from typing import Dict, List, Optional
21
+
22
+ from transformers import PreTrainedTokenizer
23
+
24
+ class ChessTokenizer(PreTrainedTokenizer):
25
+
26
+ model_input_names = ["input_ids", "attention_mask"]
27
+
28
+ # Special tokens
29
+ PAD_TOKEN = "[PAD]"
30
+ BOS_TOKEN = "[BOS]"
31
+ EOS_TOKEN = "[EOS]"
32
+ UNK_TOKEN = "[UNK]"
33
+
34
+ # Regex to parse the extended UCI format
35
+ # Groups: 1=Piece, 2=Source, 3=Dest, 4=Suffix
36
+ MOVE_REGEX = re.compile(r"([WB][PNBRQK])([a-h][1-8])([a-h][1-8])(.*)")
37
+
38
+ def __init__(
39
+ self,
40
+ vocab_file: Optional[str] = None,
41
+ vocab: Optional[Dict[str, int]] = None,
42
+ **kwargs,
43
+ ):
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
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
+ if vocab is not None:
56
+ self._vocab = vocab
57
+ elif vocab_file is not None and os.path.exists(vocab_file):
58
+ with open(vocab_file, "r", encoding="utf-8") as f:
59
+ self._vocab = json.load(f)
60
+ else:
61
+ self._vocab = self._create_atomic_vocab()
62
+
63
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
64
+
65
+ super().__init__(
66
+ pad_token=self._pad_token,
67
+ bos_token=self._bos_token,
68
+ eos_token=self._eos_token,
69
+ unk_token=self._unk_token,
70
+ **kwargs,
71
+ )
72
+
73
+ def _create_atomic_vocab(self) -> Dict[str, int]:
74
+ """
75
+ Manually builds the vocabulary because we know the rules of Chess.
76
+ We don't need to learn this from the dataset.
77
+ """
78
+ vocab = {}
79
+ idx = 0
80
+
81
+ # 1. Special Tokens
82
+ for token in [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]:
83
+ vocab[token] = idx
84
+ idx += 1
85
+
86
+ # 2. Pieces (Color + Type)
87
+ colors = ['W', 'B']
88
+ pieces = ['P', 'N', 'B', 'R', 'Q', 'K']
89
+ for c in colors:
90
+ for p in pieces:
91
+ vocab[f"{c}{p}"] = idx
92
+ idx += 1
93
+
94
+ # 3. Squares (a1 to h8)
95
+ files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
96
+ ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
97
+ for f in files:
98
+ for r in ranks:
99
+ vocab[f"{f}{r}"] = idx
100
+ idx += 1
101
+
102
+ # 4. Common Suffixes (derived from Lichess notation)
103
+ # (x)=capture, (+)=check, (#)=mate, (o)=castling
104
+ suffixes = ["(x)", "(+)", "(+*)", "(o)", "(O)", "=", "=Q", "=R", "=B", "=N"]
105
+ for s in suffixes:
106
+ vocab[s] = idx
107
+ idx += 1
108
+
109
+ return vocab
110
+
111
+ @property
112
+ def vocab_size(self) -> int:
113
+ return len(self._vocab)
114
+
115
+ def get_vocab(self) -> Dict[str, int]:
116
+ return dict(self._vocab)
117
+
118
+ def _tokenize(self, text: str) -> List[str]:
119
+ """
120
+ Splits a string of moves into atomic tokens.
121
+ "WPe2e4" -> ["WP", "e2", "e4"]
122
+ """
123
+ raw_moves = text.strip().split()
124
+ tokens = []
125
+
126
+ for move in raw_moves:
127
+ match = self.MOVE_REGEX.match(move)
128
+ if match:
129
+ # Add piece, source, dest
130
+ tokens.extend([match.group(1), match.group(2), match.group(3)])
131
+ # Add suffix if it exists
132
+ suffix = match.group(4)
133
+ if suffix:
134
+ tokens.append(suffix)
135
+ else:
136
+ # Fallback for weird formatting (or UNK)
137
+ tokens.append(move)
138
+
139
+ return tokens
140
+
141
+ def _convert_token_to_id(self, token: str) -> int:
142
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN))
143
+
144
+ def _convert_id_to_token(self, index: int) -> str:
145
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
146
+
147
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
148
+ """
149
+ Reconstructs moves from atomic tokens.
150
+ This is tricky because we need to join them without spaces,
151
+ but add spaces between actual moves.
152
+ """
153
+ out = []
154
+ current_move = []
155
+
156
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
157
+
158
+ for t in tokens:
159
+ if t in special:
160
+ continue
161
+
162
+ current_move.append(t)
163
+
164
+ # Logic to decide when a move ends
165
+ # A move usually ends after a Suffix OR after a Destination square if no suffix follows
166
+ # This heuristic is simple: if we have a piece, src, and dest, check next token
167
+
168
+ # Simplified reconstruction:
169
+ # Just join everything and use a heuristic to insert spaces?
170
+ # Better: The model generates atomic tokens.
171
+ # We know a move starts with [WB][PNBRQK].
172
+
173
+ # Robust reconstruction approach:
174
+ full_str = "".join([t for t in tokens if t not in special])
175
+
176
+ # Insert space before every Piece token (except the first one)
177
+ # Regex lookbehind isn't strictly necessary, we can just replace
178
+ formatted = re.sub(r'(?<!^)([WB][PNBRQK])', r' \1', full_str)
179
+
180
+ return formatted
181
+
182
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
183
+ if not os.path.isdir(save_directory):
184
+ os.makedirs(save_directory, exist_ok=True)
185
+ vocab_file = os.path.join(
186
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + "vocab.json"
187
+ )
188
+ with open(vocab_file, "w", encoding="utf-8") as f:
189
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
190
+ return (vocab_file,)
191
+
192
+ # We don't really need build_vocab_from_dataset anymore as we hardcoded the rules,
193
+ # but we keep the method signature to satisfy the template.
194
+ @classmethod
195
+ def build_vocab_from_dataset(cls, *args, **kwargs):
196
+ print("Note: Atomic tokenizer uses a static vocabulary rule set.")
197
+ return cls()
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,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "WP": 4,
7
+ "WN": 5,
8
+ "WB": 6,
9
+ "WR": 7,
10
+ "WQ": 8,
11
+ "WK": 9,
12
+ "BP": 10,
13
+ "BN": 11,
14
+ "BB": 12,
15
+ "BR": 13,
16
+ "BQ": 14,
17
+ "BK": 15,
18
+ "a1": 16,
19
+ "a2": 17,
20
+ "a3": 18,
21
+ "a4": 19,
22
+ "a5": 20,
23
+ "a6": 21,
24
+ "a7": 22,
25
+ "a8": 23,
26
+ "b1": 24,
27
+ "b2": 25,
28
+ "b3": 26,
29
+ "b4": 27,
30
+ "b5": 28,
31
+ "b6": 29,
32
+ "b7": 30,
33
+ "b8": 31,
34
+ "c1": 32,
35
+ "c2": 33,
36
+ "c3": 34,
37
+ "c4": 35,
38
+ "c5": 36,
39
+ "c6": 37,
40
+ "c7": 38,
41
+ "c8": 39,
42
+ "d1": 40,
43
+ "d2": 41,
44
+ "d3": 42,
45
+ "d4": 43,
46
+ "d5": 44,
47
+ "d6": 45,
48
+ "d7": 46,
49
+ "d8": 47,
50
+ "e1": 48,
51
+ "e2": 49,
52
+ "e3": 50,
53
+ "e4": 51,
54
+ "e5": 52,
55
+ "e6": 53,
56
+ "e7": 54,
57
+ "e8": 55,
58
+ "f1": 56,
59
+ "f2": 57,
60
+ "f3": 58,
61
+ "f4": 59,
62
+ "f5": 60,
63
+ "f6": 61,
64
+ "f7": 62,
65
+ "f8": 63,
66
+ "g1": 64,
67
+ "g2": 65,
68
+ "g3": 66,
69
+ "g4": 67,
70
+ "g5": 68,
71
+ "g6": 69,
72
+ "g7": 70,
73
+ "g8": 71,
74
+ "h1": 72,
75
+ "h2": 73,
76
+ "h3": 74,
77
+ "h4": 75,
78
+ "h5": 76,
79
+ "h6": 77,
80
+ "h7": 78,
81
+ "h8": 79,
82
+ "(x)": 80,
83
+ "(+)": 81,
84
+ "(+*)": 82,
85
+ "(o)": 83,
86
+ "(O)": 84,
87
+ "=": 85,
88
+ "=Q": 86,
89
+ "=R": 87,
90
+ "=B": 88,
91
+ "=N": 89
92
+ }