Tome1 commited on
Commit
ea4db11
·
verified ·
1 Parent(s): 859c2f4

Chess Challenge submission by Tome1

Browse files
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-tomin-v6
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Tome1](https://huggingface.co/Tome1)
17
+ - **Parameters**: 876,800
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 132
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 5
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 4,
14
+ "n_inner": 384,
15
+ "n_layer": 5,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.4",
19
+ "use_cache": false,
20
+ "vocab_size": 132
21
+ }
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 2
7
+ ],
8
+ "pad_token_id": 0,
9
+ "top_k": 20,
10
+ "top_p": 0.9,
11
+ "transformers_version": "4.57.4",
12
+ "use_cache": false
13
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1559a94257b77e9d4e7b09791773412f450a3ba790f4fa2278b68a72ae2b6c2d
3
+ size 3512624
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 each move as a single token using the extended UCI notation
5
+ from the Lichess dataset (e.g., WPe2e4, BNg8f6).
6
+
7
+ The dataset format uses:
8
+ - W/B prefix for White/Black
9
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
10
+ - Source and destination squares (e.g., e2e4)
11
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Dict, List, Optional
20
+ import re
21
+
22
+ from transformers import PreTrainedTokenizer
23
+
24
+
25
+ class ChessTokenizer(PreTrainedTokenizer):
26
+ """
27
+ A custom tokenizer for chess moves using extended UCI notation.
28
+
29
+ This tokenizer maps each possible chess move to a unique token ID.
30
+ The vocabulary is built from the training dataset to ensure all moves
31
+ encountered during training have a corresponding token.
32
+
33
+ Example:
34
+ >>> tokenizer = ChessTokenizer()
35
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
36
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
37
+ """
38
+
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+ vocab_files_names = {"vocab_file": "vocab.json"}
41
+
42
+ # Special tokens
43
+ PAD_TOKEN = "[PAD]"
44
+ BOS_TOKEN = "[BOS]"
45
+ EOS_TOKEN = "[EOS]"
46
+ UNK_TOKEN = "[UNK]"
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file: Optional[str] = None,
51
+ vocab: Optional[Dict[str, int]] = None,
52
+ **kwargs,
53
+ ):
54
+ """
55
+ Initialize the chess tokenizer.
56
+
57
+ Args:
58
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
59
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
60
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
61
+ """
62
+ # Initialize special tokens
63
+ self._pad_token = self.PAD_TOKEN
64
+ self._bos_token = self.BOS_TOKEN
65
+ self._eos_token = self.EOS_TOKEN
66
+ self._unk_token = self.UNK_TOKEN
67
+
68
+ # Remove any duplicate special-token entries passed through kwargs
69
+ # to avoid "multiple values for keyword" errors when loading from disk.
70
+ kwargs.pop("pad_token", None)
71
+ kwargs.pop("bos_token", None)
72
+ kwargs.pop("eos_token", None)
73
+ kwargs.pop("unk_token", None)
74
+
75
+
76
+ self._vocab = self._create_default_vocab()
77
+ # Updated regex: destination square may have promotion (e.g., h1Q)
78
+ self.token_regex = re.compile(r"([a-h][1-8])([a-h][1-8])(?:\\(([QRBN])\\))?")
79
+
80
+ # Create reverse mapping
81
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
82
+
83
+ # Call parent init AFTER setting up vocab
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 a minimal default vocabulary with just special tokens.
95
+
96
+ For the full vocabulary, use `build_vocab_from_dataset()`.
97
+ This minimal vocab is just a placeholder - you should build from data.
98
+ """
99
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
100
+ #vocab = {token: idx for idx, token in enumerate(special_tokens)}
101
+
102
+ tokens = []
103
+ for c in "abcdefgh":
104
+ for r in "12345678":
105
+ sub_move = f"{c}{r}"
106
+ tokens.append(sub_move)
107
+ promotions = ["Q", "R", "B", "N"]
108
+
109
+ tokens = special_tokens + tokens + [ f"{h}{v}{p}" for h in "abcdefgh" for v in "18" for p in promotions ]
110
+
111
+ vocab = {token: idx for idx, token in enumerate(tokens)}
112
+
113
+ return vocab
114
+
115
+
116
+
117
+ @property
118
+ def vocab_size(self) -> int:
119
+ """Return the size of the vocabulary."""
120
+ return len(self._vocab)
121
+
122
+ def get_vocab(self) -> Dict[str, int]:
123
+ """Return the vocabulary as a dictionary."""
124
+ return dict(self._vocab)
125
+
126
+ def _tokenize(self, text: str) -> List[str]:
127
+ """
128
+ Tokenize a string of moves into a list of tokens.
129
+
130
+ Args:
131
+ text: A string of space-separated moves.
132
+
133
+ Returns:
134
+ List of move tokens.
135
+ """
136
+ moves = text.strip().split()
137
+ tokens = []
138
+ for move in moves:
139
+ match = self.token_regex.match(move[2:]) if len(move) > 2 else None # skip color/piece prefix
140
+ if match:
141
+ src = match.group(1)
142
+ dst = match.group(2)
143
+ promo = match.group(3)
144
+ if promo:
145
+ dst = dst + promo
146
+ tokens.extend([src, dst])
147
+ else:
148
+ tokens.append(self.UNK_TOKEN)
149
+ return tokens
150
+
151
+ def _convert_token_to_id(self, token: str) -> int:
152
+ """Convert a token to its ID."""
153
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
154
+
155
+ def _convert_id_to_token(self, index: int) -> str:
156
+ """Convert an ID to its token."""
157
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
158
+
159
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
160
+ """Convert a list of tokens back to a string."""
161
+ # Filter out special tokens for cleaner output
162
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
163
+ return " ".join(t for t in tokens if t not in special)
164
+
165
+ def save_vocabulary(
166
+ self,
167
+ save_directory: str,
168
+ filename_prefix: Optional[str] = None,
169
+ ) -> tuple:
170
+ """
171
+ Save the vocabulary to a JSON file.
172
+
173
+ Args:
174
+ save_directory: Directory to save the vocabulary.
175
+ filename_prefix: Optional prefix for the filename.
176
+
177
+ Returns:
178
+ Tuple containing the path to the saved vocabulary file.
179
+ """
180
+ if not os.path.isdir(save_directory):
181
+ os.makedirs(save_directory, exist_ok=True)
182
+
183
+ vocab_file = os.path.join(
184
+ save_directory,
185
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
186
+ )
187
+
188
+ with open(vocab_file, "w", encoding="utf-8") as f:
189
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
190
+
191
+ return (vocab_file,)
192
+
193
+
194
+ def count_vocab_from_dataset(
195
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
196
+ split: str = "train",
197
+ column: str = "text",
198
+ max_samples: Optional[int] = 10000,
199
+ ) -> Dict[str, int]:
200
+ """
201
+ Count token frequencies in a dataset (useful for vocabulary analysis).
202
+
203
+ Args:
204
+ dataset_name: Name of the dataset on Hugging Face Hub.
205
+ split: Dataset split to use.
206
+ column: Column containing the game strings.
207
+ max_samples: Maximum number of samples to process.
208
+
209
+ Returns:
210
+ Dictionary mapping tokens to their frequencies.
211
+ """
212
+ from collections import Counter
213
+ from datasets import load_dataset
214
+
215
+ dataset = load_dataset(dataset_name, split=split)
216
+
217
+ if max_samples is not None:
218
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
219
+
220
+ token_counts = Counter()
221
+
222
+ for example in dataset:
223
+ moves = example[column].strip().split()
224
+ token_counts.update(moves)
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,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "a1Q": 68,
71
+ "a1R": 69,
72
+ "a1B": 70,
73
+ "a1N": 71,
74
+ "a8Q": 72,
75
+ "a8R": 73,
76
+ "a8B": 74,
77
+ "a8N": 75,
78
+ "b1Q": 76,
79
+ "b1R": 77,
80
+ "b1B": 78,
81
+ "b1N": 79,
82
+ "b8Q": 80,
83
+ "b8R": 81,
84
+ "b8B": 82,
85
+ "b8N": 83,
86
+ "c1Q": 84,
87
+ "c1R": 85,
88
+ "c1B": 86,
89
+ "c1N": 87,
90
+ "c8Q": 88,
91
+ "c8R": 89,
92
+ "c8B": 90,
93
+ "c8N": 91,
94
+ "d1Q": 92,
95
+ "d1R": 93,
96
+ "d1B": 94,
97
+ "d1N": 95,
98
+ "d8Q": 96,
99
+ "d8R": 97,
100
+ "d8B": 98,
101
+ "d8N": 99,
102
+ "e1Q": 100,
103
+ "e1R": 101,
104
+ "e1B": 102,
105
+ "e1N": 103,
106
+ "e8Q": 104,
107
+ "e8R": 105,
108
+ "e8B": 106,
109
+ "e8N": 107,
110
+ "f1Q": 108,
111
+ "f1R": 109,
112
+ "f1B": 110,
113
+ "f1N": 111,
114
+ "f8Q": 112,
115
+ "f8R": 113,
116
+ "f8B": 114,
117
+ "f8N": 115,
118
+ "g1Q": 116,
119
+ "g1R": 117,
120
+ "g1B": 118,
121
+ "g1N": 119,
122
+ "g8Q": 120,
123
+ "g8R": 121,
124
+ "g8B": 122,
125
+ "g8N": 123,
126
+ "h1Q": 124,
127
+ "h1R": 125,
128
+ "h1B": 126,
129
+ "h1N": 127,
130
+ "h8Q": 128,
131
+ "h8R": 129,
132
+ "h8B": 130,
133
+ "h8N": 131
134
+ }