Ryn11H commited on
Commit
7ab0ed4
·
verified ·
1 Parent(s): 6e67b7f

Chess Challenge submission by Ryn11H

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 +183 -0
  6. tokenizer_config.json +50 -0
  7. vocab.json +0 -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-Rayan-FATNASSI
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [Ryn11H](https://huggingface.co/Ryn11H)
17
+ - **Parameters**: 878,016
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 5000
24
+ - **Embedding dim**: 96
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.0,
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": 96,
13
+ "n_head": 4,
14
+ "n_inner": 288,
15
+ "n_layer": 4,
16
+ "pad_token_id": 0,
17
+ "tie_weights": true,
18
+ "transformers_version": "4.57.3",
19
+ "vocab_size": 5000
20
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33ddf78d2a1fe7ba8601f3ebf5fa4254cf2b64524e98e74c63c00f462a2696dc
3
+ size 3516392
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,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ Move-level tokenizer:
5
+ - Each move string is ONE token, e.g. "WPe2e4", "BNg8f6", "WBb5c6(x)".
6
+
7
+ Key improvement vs baseline:
8
+ - Adds `max_vocab_size` to cap vocabulary size (very important for <1M params).
9
+ - Keeps the TOP-K most frequent moves (after min_frequency filter).
10
+ - Registers for AutoTokenizer so server-side loading works.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from typing import Dict, List, Optional, Tuple
18
+
19
+ from transformers import PreTrainedTokenizer
20
+
21
+
22
+ class ChessTokenizer(PreTrainedTokenizer):
23
+ model_input_names = ["input_ids", "attention_mask"]
24
+ vocab_files_names = {"vocab_file": "vocab.json"}
25
+
26
+ # Special tokens
27
+ PAD_TOKEN = "[PAD]"
28
+ BOS_TOKEN = "[BOS]"
29
+ EOS_TOKEN = "[EOS]"
30
+ UNK_TOKEN = "[UNK]"
31
+
32
+ def __init__(
33
+ self,
34
+ vocab_file: Optional[str] = None,
35
+ vocab: Optional[Dict[str, int]] = None,
36
+ **kwargs,
37
+ ):
38
+ # Set special tokens
39
+ self._pad_token = self.PAD_TOKEN
40
+ self._bos_token = self.BOS_TOKEN
41
+ self._eos_token = self.EOS_TOKEN
42
+ self._unk_token = self.UNK_TOKEN
43
+
44
+ # Remove duplicates in kwargs (important when loading)
45
+ kwargs.pop("pad_token", None)
46
+ kwargs.pop("bos_token", None)
47
+ kwargs.pop("eos_token", None)
48
+ kwargs.pop("unk_token", None)
49
+
50
+ # Load vocab
51
+ if vocab is not None:
52
+ self._vocab = vocab
53
+ elif vocab_file is not None and os.path.exists(vocab_file):
54
+ with open(vocab_file, "r", encoding="utf-8") as f:
55
+ self._vocab = json.load(f)
56
+ else:
57
+ self._vocab = self._create_default_vocab()
58
+
59
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
60
+
61
+ super().__init__(
62
+ pad_token=self._pad_token,
63
+ bos_token=self._bos_token,
64
+ eos_token=self._eos_token,
65
+ unk_token=self._unk_token,
66
+ **kwargs,
67
+ )
68
+
69
+ def _create_default_vocab(self) -> Dict[str, int]:
70
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
71
+ return {tok: i for i, tok in enumerate(special_tokens)}
72
+
73
+ @classmethod
74
+ def build_vocab_from_iterator(
75
+ cls,
76
+ iterator,
77
+ min_frequency: int = 1,
78
+ max_vocab_size: int = 5000,
79
+ ) -> "ChessTokenizer":
80
+ """
81
+ Build vocabulary from an iterator of game strings.
82
+
83
+ Strategy:
84
+ - Count move frequency
85
+ - Filter by min_frequency
86
+ - Take TOP-K most frequent moves (K = max_vocab_size - #special_tokens)
87
+
88
+ This avoids vocab explosion (which breaks the <1M parameter constraint).
89
+ """
90
+ from collections import Counter
91
+
92
+ token_counts = Counter()
93
+ for game in iterator:
94
+ moves = game.strip().split()
95
+ token_counts.update(moves)
96
+
97
+ # Filter by frequency
98
+ items = [(tok, c) for tok, c in token_counts.items() if c >= min_frequency]
99
+
100
+ # Sort by frequency desc then token for reproducibility
101
+ items.sort(key=lambda x: (-x[1], x[0]))
102
+
103
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
104
+ budget = max_vocab_size - len(special_tokens)
105
+ if budget <= 0:
106
+ raise ValueError("max_vocab_size must be > number of special tokens")
107
+
108
+ top_tokens = [tok for tok, _ in items[:budget]]
109
+
110
+ vocab = {tok: i for i, tok in enumerate(special_tokens + top_tokens)}
111
+ return cls(vocab=vocab)
112
+
113
+ @classmethod
114
+ def build_vocab_from_dataset(
115
+ cls,
116
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
117
+ split: str = "train",
118
+ column: str = "text",
119
+ min_frequency: int = 500,
120
+ max_samples: Optional[int] = 100000,
121
+ max_vocab_size: int = 5000,
122
+ ) -> "ChessTokenizer":
123
+ """
124
+ Build vocabulary from a HF dataset.
125
+
126
+ IMPORTANT:
127
+ - `max_vocab_size` caps final vocab size (including special tokens).
128
+ - `min_frequency` filters extremely rare moves before top-k selection.
129
+ """
130
+ from datasets import load_dataset
131
+
132
+ dataset = load_dataset(dataset_name, split=split)
133
+
134
+ if max_samples is not None:
135
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
136
+
137
+ def game_iterator():
138
+ for example in dataset:
139
+ yield example[column]
140
+
141
+ return cls.build_vocab_from_iterator(
142
+ game_iterator(),
143
+ min_frequency=min_frequency,
144
+ max_vocab_size=max_vocab_size,
145
+ )
146
+
147
+ @property
148
+ def vocab_size(self) -> int:
149
+ return len(self._vocab)
150
+
151
+ def get_vocab(self) -> Dict[str, int]:
152
+ return dict(self._vocab)
153
+
154
+ def _tokenize(self, text: str) -> List[str]:
155
+ return text.strip().split()
156
+
157
+ def _convert_token_to_id(self, token: str) -> int:
158
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
159
+
160
+ def _convert_id_to_token(self, index: int) -> str:
161
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
162
+
163
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
164
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
165
+ return " ".join(t for t in tokens if t not in special)
166
+
167
+ def save_vocabulary(
168
+ self,
169
+ save_directory: str,
170
+ filename_prefix: Optional[str] = None,
171
+ ) -> Tuple[str]:
172
+ os.makedirs(save_directory, exist_ok=True)
173
+ vocab_file = os.path.join(
174
+ save_directory,
175
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
176
+ )
177
+ with open(vocab_file, "w", encoding="utf-8") as f:
178
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
179
+ return (vocab_file,)
180
+
181
+
182
+ # IMPORTANT for server-side loading on HF
183
+ ChessTokenizer.register_for_auto_class("AutoTokenizer")
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
The diff for this file is too large to render. See raw diff