minhdc commited on
Commit
91eb51f
·
verified ·
1 Parent(s): e663058

Chess Challenge submission by minhdc

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 +217 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +70 -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-duc-v2
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [minhdc](https://huggingface.co/minhdc)
17
+ - **Parameters**: 996,976
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 68
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.05,
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": 360,
15
+ "n_layer": 6,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.6",
19
+ "vocab_size": 68
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f66fca9e2271541c813f639110a30971ce357a71c6d695d7bffca3d0d2673add
3
+ size 3994352
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,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized Chess Tokenizer using pure UCI notation.
3
+
4
+ This achieves ~84 vocab size by:
5
+ 1. Using only squares (a1-h8) and promotion pieces (q,r,b,n)
6
+ 2. Decomposing moves into from_square, to_square, (optional) promotion
7
+ 3. No piece types, no color, no annotations
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ from typing import Dict, List, Optional
15
+
16
+ from transformers import PreTrainedTokenizer
17
+
18
+
19
+ class ChessTokenizer(PreTrainedTokenizer):
20
+
21
+ model_input_names = ["input_ids", "attention_mask"]
22
+ vocab_files_names = {"vocab_file": "vocab.json"}
23
+
24
+ # Special tokens
25
+ PAD_TOKEN = "[PAD]"
26
+ BOS_TOKEN = "[BOS]"
27
+ EOS_TOKEN = "[EOS]"
28
+ UNK_TOKEN = "[UNK]"
29
+
30
+ def __init__(
31
+ self,
32
+ vocab_file: Optional[str] = None,
33
+ vocab: Optional[Dict[str, int]] = None,
34
+ **kwargs,
35
+ ):
36
+ # Initialize special tokens
37
+ self._pad_token = self.PAD_TOKEN
38
+ self._bos_token = self.BOS_TOKEN
39
+ self._eos_token = self.EOS_TOKEN
40
+ self._unk_token = self.UNK_TOKEN
41
+
42
+ # Remove duplicates from kwargs
43
+ kwargs.pop("pad_token", None)
44
+ kwargs.pop("bos_token", None)
45
+ kwargs.pop("eos_token", None)
46
+ kwargs.pop("unk_token", None)
47
+
48
+ # Load or create vocabulary
49
+ if vocab is not None:
50
+ self._vocab = vocab
51
+ elif vocab_file is not None and os.path.exists(vocab_file):
52
+ with open(vocab_file, "r", encoding="utf-8") as f:
53
+ self._vocab = json.load(f)
54
+ else:
55
+ self._vocab = self._create_default_vocab()
56
+
57
+ # Create reverse mapping
58
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
59
+
60
+ super().__init__(
61
+ pad_token=self._pad_token,
62
+ bos_token=self._bos_token,
63
+ eos_token=self._eos_token,
64
+ unk_token=self._unk_token,
65
+ **kwargs,
66
+ )
67
+
68
+ def _create_default_vocab(self) -> Dict[str, int]:
69
+ """
70
+ Create vocabulary with all possible squares and promotion pieces.
71
+ This ensures deterministic vocab size of exactly 72 tokens.
72
+ """
73
+ tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
74
+
75
+ # All squares a1-h8
76
+ for file in 'abcdefgh':
77
+ for rank in '12345678':
78
+ tokens.append(f"{file}{rank}")
79
+
80
+ # Promotion pieces (lowercase for UCI)
81
+ tokens.extend(['q', 'r', 'b', 'n'])
82
+
83
+ vocab = {token: idx for idx, token in enumerate(tokens)}
84
+ return vocab
85
+
86
+ @classmethod
87
+ def build_vocab_from_dataset(
88
+ cls,
89
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
90
+ split: str = "train",
91
+ column: str = "text",
92
+ min_frequency: int = 1,
93
+ max_samples: Optional[int] = 100000,
94
+ ) -> "ChessTokenizer":
95
+ """
96
+ Build tokenizer from dataset by converting to UCI format.
97
+
98
+ This will create a vocabulary of ~72-84 tokens.
99
+ """
100
+ from datasets import load_dataset
101
+ from collections import Counter
102
+
103
+ dataset = load_dataset(dataset_name, split=split)
104
+
105
+ if max_samples is not None:
106
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
107
+
108
+ token_counts = Counter()
109
+
110
+ # Process games and extract UCI components
111
+ for example in dataset:
112
+ moves = example[column].strip().split()
113
+ for move in moves:
114
+ # Convert extended UCI to decomposed UCI
115
+ uci_tokens = cls._extended_to_uci_tokens(move)
116
+ token_counts.update(uci_tokens)
117
+
118
+ # Filter by frequency
119
+ tokens = [
120
+ token for token, count in token_counts.items()
121
+ if count >= min_frequency
122
+ ]
123
+
124
+ # Sort for reproducibility
125
+ tokens = sorted(set(tokens))
126
+
127
+ # Build vocabulary
128
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
129
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
130
+
131
+ return cls(vocab=vocab)
132
+
133
+ @staticmethod
134
+ def _extended_to_uci_tokens(move: str) -> List[str]:
135
+ """
136
+ Convert extended UCI format to decomposed UCI tokens.
137
+
138
+ Input: "WPe2e4" or "BQd8h4(x+)" or "WPe7e8=Q"
139
+ Output: ["e2", "e4"] or ["d8", "h4"] or ["e7", "e8", "q"]
140
+ """
141
+ if len(move) < 6:
142
+ return []
143
+
144
+ # Extract squares (positions 2-6)
145
+ from_sq = move[2:4]
146
+ to_sq = move[4:6]
147
+
148
+ tokens = [from_sq, to_sq]
149
+
150
+ # Check for promotion
151
+ if "=" in move:
152
+ promo_idx = move.index("=")
153
+ if promo_idx + 1 < len(move):
154
+ promo = move[promo_idx + 1].lower()
155
+ if promo in 'qrbn':
156
+ tokens.append(promo)
157
+
158
+ return tokens
159
+
160
+ @property
161
+ def vocab_size(self) -> int:
162
+ return len(self._vocab)
163
+
164
+ def get_vocab(self) -> Dict[str, int]:
165
+ return dict(self._vocab)
166
+
167
+ def _tokenize(self, text: str) -> List[str]:
168
+ """
169
+ Tokenize a string of moves.
170
+
171
+ Input can be either:
172
+ - Extended UCI: "WPe2e4 BPe7e5"
173
+ - Decomposed UCI: "e2 e4 e7 e5"
174
+ """
175
+ tokens = text.strip().split()
176
+
177
+ # If tokens look like extended UCI (start with W/B and piece letter)
178
+ # convert them to decomposed format
179
+ result = []
180
+ for token in tokens:
181
+ if len(token) >= 6 and token[0] in 'WB' and token[1] in 'PNBRQK':
182
+ # Extended format - decompose it
183
+ result.extend(self._extended_to_uci_tokens(token))
184
+ else:
185
+ # Already in simple format or is a square/promotion
186
+ result.append(token)
187
+
188
+ return result
189
+
190
+ def _convert_token_to_id(self, token: str) -> int:
191
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
192
+
193
+ def _convert_id_to_token(self, index: int) -> str:
194
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
195
+
196
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
197
+ """Convert tokens back to string (space-separated)."""
198
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
199
+ return " ".join(t for t in tokens if t not in special)
200
+
201
+ def save_vocabulary(
202
+ self,
203
+ save_directory: str,
204
+ filename_prefix: Optional[str] = None,
205
+ ) -> tuple:
206
+ if not os.path.isdir(save_directory):
207
+ os.makedirs(save_directory, exist_ok=True)
208
+
209
+ vocab_file = os.path.join(
210
+ save_directory,
211
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
212
+ )
213
+
214
+ with open(vocab_file, "w", encoding="utf-8") as f:
215
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
216
+
217
+ return (vocab_file,)
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,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }