alexandreduplessis commited on
Commit
dfaa025
·
verified ·
1 Parent(s): a61b6a8

Chess Challenge submission by alexandreduplessis

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 +194 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +75 -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
+ # chesstoktok
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [alexandreduplessis](https://huggingface.co/alexandreduplessis)
17
+ - **Parameters**: 703,872
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 73
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 4
26
+ - **Heads**: 4
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "dropout": 0.05,
7
+ "eos_token_id": 2,
8
+ "layer_norm_epsilon": 1e-05,
9
+ "model_type": "chess_transformer",
10
+ "n_ctx": 256,
11
+ "n_embd": 128,
12
+ "n_head": 4,
13
+ "n_inner": 384,
14
+ "n_layer": 4,
15
+ "pad_token_id": 0,
16
+ "tie_weights": true,
17
+ "torch_dtype": "float32",
18
+ "transformers_version": "4.55.0",
19
+ "vocab_size": 73
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:375a8dd55b7164613a088c79e5dcf56fcd0a753f4abb07b7056f9a518af71d9d
3
+ size 2819888
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,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ from transformers import PreTrainedTokenizer
9
+
10
+
11
+ class ChessTokenizer(PreTrainedTokenizer):
12
+
13
+ model_input_names = ["input_ids", "attention_mask"]
14
+ vocab_files_names = {"vocab_file": "vocab.json"}
15
+
16
+ # Special tokens
17
+ PAD_TOKEN = "[PAD]"
18
+ BOS_TOKEN = "[BOS]"
19
+ EOS_TOKEN = "[EOS]"
20
+ UNK_TOKEN = "[UNK]"
21
+
22
+ # Structure token
23
+ MOVE_TOKEN = "[MOVE]"
24
+
25
+ _MOVE_RE = re.compile(
26
+ r'^(?P<color>[WB])(?P<piece>[PNBRQK])(?P<from>[a-h][1-8])(?P<to>[a-h][1-8])(?P<rest>.*)$'
27
+ )
28
+ _PROMO_RE = re.compile(r'=?([QRBNqrbn])')
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 any duplicate special-token entries passed through 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
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
58
+
59
+ super().__init__(
60
+ pad_token=self._pad_token,
61
+ bos_token=self._bos_token,
62
+ eos_token=self._eos_token,
63
+ unk_token=self._unk_token,
64
+ **kwargs,
65
+ )
66
+
67
+ def _create_default_vocab(self) -> Dict[str, int]:
68
+ special = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.MOVE_TOKEN]
69
+ return {t: i for i, t in enumerate(special)}
70
+
71
+ @classmethod
72
+ def build_structured_vocab(cls) -> "ChessTokenizer":
73
+ special = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN, cls.MOVE_TOKEN]
74
+
75
+ files = "abcdefgh"
76
+ ranks = "12345678"
77
+ squares = [f"{f}{r}" for f in files for r in ranks] # 64
78
+
79
+ promo = [f"promo_{p}" for p in ("q", "r", "b", "n")]
80
+
81
+ tokens = special + squares + promo
82
+ vocab = {t: i for i, t in enumerate(tokens)}
83
+ return cls(vocab=vocab)
84
+
85
+ @classmethod
86
+ def build_vocab_from_dataset(
87
+ cls,
88
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
89
+ split: str = "train",
90
+ column: str = "text",
91
+ min_frequency: int = 500,
92
+ max_samples: Optional[int] = 100000,
93
+ ) -> "ChessTokenizer":
94
+ return cls.build_structured_vocab()
95
+
96
+ @property
97
+ def vocab_size(self) -> int:
98
+ return len(self._vocab)
99
+
100
+ def get_vocab(self) -> Dict[str, int]:
101
+ return dict(self._vocab)
102
+
103
+ def _convert_token_to_id(self, token: str) -> int:
104
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
105
+
106
+ def _convert_id_to_token(self, index: int) -> str:
107
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
108
+
109
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
110
+ drop = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
111
+ return " ".join(t for t in tokens if t not in drop)
112
+
113
+ def _decompose_one_move(self, move_tok: str) -> List[str]:
114
+ m = self._MOVE_RE.match(move_tok)
115
+ if not m:
116
+ return [self.UNK_TOKEN]
117
+
118
+ from_sq = m.group("from")
119
+ to_sq = m.group("to")
120
+ rest = m.group("rest") or ""
121
+
122
+ out = [self.MOVE_TOKEN, from_sq, to_sq]
123
+
124
+ # Promotion detection (best-effort)
125
+ pm = self._PROMO_RE.search(rest)
126
+ if pm:
127
+ p = pm.group(1).lower()
128
+ if p in ("q", "r", "b", "n"):
129
+ out.append(f"promo_{p}")
130
+
131
+ return out
132
+
133
+ def _tokenize(self, text: str) -> List[str]:
134
+ text = text.strip()
135
+ if not text:
136
+ return []
137
+
138
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.MOVE_TOKEN}
139
+
140
+ if " " not in text:
141
+ if text in special:
142
+ return [text]
143
+ if text in self._vocab:
144
+ return [text]
145
+ return self._decompose_one_move(text)
146
+
147
+ out: List[str] = []
148
+ for part in text.split():
149
+ if part in special:
150
+ out.append(part)
151
+ elif part in self._vocab:
152
+ out.append(part)
153
+ else:
154
+ out.extend(self._decompose_one_move(part))
155
+ return out
156
+
157
+ def save_vocabulary(
158
+ self,
159
+ save_directory: str,
160
+ filename_prefix: Optional[str] = None,
161
+ ) -> Tuple[str]:
162
+ if not os.path.isdir(save_directory):
163
+ os.makedirs(save_directory, exist_ok=True)
164
+
165
+ vocab_file = os.path.join(
166
+ save_directory,
167
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
168
+ )
169
+
170
+ with open(vocab_file, "w", encoding="utf-8") as f:
171
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
172
+
173
+ return (vocab_file,)
174
+
175
+
176
+ def count_vocab_from_dataset(
177
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
178
+ split: str = "train",
179
+ column: str = "text",
180
+ max_samples: Optional[int] = 10000,
181
+ ) -> Dict[str, int]:
182
+ from collections import Counter
183
+ from datasets import load_dataset
184
+
185
+ dataset = load_dataset(dataset_name, split=split)
186
+ if max_samples is not None:
187
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
188
+
189
+ token_counts = Counter()
190
+ for example in dataset:
191
+ moves = example[column].strip().split()
192
+ token_counts.update(moves)
193
+
194
+ 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,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "[MOVE]": 4,
7
+ "a1": 5,
8
+ "a2": 6,
9
+ "a3": 7,
10
+ "a4": 8,
11
+ "a5": 9,
12
+ "a6": 10,
13
+ "a7": 11,
14
+ "a8": 12,
15
+ "b1": 13,
16
+ "b2": 14,
17
+ "b3": 15,
18
+ "b4": 16,
19
+ "b5": 17,
20
+ "b6": 18,
21
+ "b7": 19,
22
+ "b8": 20,
23
+ "c1": 21,
24
+ "c2": 22,
25
+ "c3": 23,
26
+ "c4": 24,
27
+ "c5": 25,
28
+ "c6": 26,
29
+ "c7": 27,
30
+ "c8": 28,
31
+ "d1": 29,
32
+ "d2": 30,
33
+ "d3": 31,
34
+ "d4": 32,
35
+ "d5": 33,
36
+ "d6": 34,
37
+ "d7": 35,
38
+ "d8": 36,
39
+ "e1": 37,
40
+ "e2": 38,
41
+ "e3": 39,
42
+ "e4": 40,
43
+ "e5": 41,
44
+ "e6": 42,
45
+ "e7": 43,
46
+ "e8": 44,
47
+ "f1": 45,
48
+ "f2": 46,
49
+ "f3": 47,
50
+ "f4": 48,
51
+ "f5": 49,
52
+ "f6": 50,
53
+ "f7": 51,
54
+ "f8": 52,
55
+ "g1": 53,
56
+ "g2": 54,
57
+ "g3": 55,
58
+ "g4": 56,
59
+ "g5": 57,
60
+ "g6": 58,
61
+ "g7": 59,
62
+ "g8": 60,
63
+ "h1": 61,
64
+ "h2": 62,
65
+ "h3": 63,
66
+ "h4": 64,
67
+ "h5": 65,
68
+ "h6": 66,
69
+ "h7": 67,
70
+ "h8": 68,
71
+ "promo_q": 69,
72
+ "promo_r": 70,
73
+ "promo_b": 71,
74
+ "promo_n": 72
75
+ }