thandre10 commited on
Commit
50975cc
·
verified ·
1 Parent(s): 768e8bc

Chess Challenge submission by thandre10

Browse files
Files changed (11) hide show
  1. README.md +31 -0
  2. config.json +24 -0
  3. data.py +253 -0
  4. model.py +438 -0
  5. model.safetensors +3 -0
  6. special_tokens_map.json +6 -0
  7. tokenizer.py +412 -0
  8. tokenizer_config.json +47 -0
  9. train.py +246 -0
  10. training_args.bin +3 -0
  11. vocab.json +85 -0
README.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # chess_trandre10_v3
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [thandre10](https://huggingface.co/thandre10)
17
+ - **Parameters**: 738,360
18
+ - **Organization**: LLM-course
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ model = AutoModelForCausalLM.from_pretrained("LLM-course/chess_trandre10_v3", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("LLM-course/chess_trandre10_v3", trust_remote_code=True)
27
+ ```
28
+
29
+ ## Evaluation
30
+
31
+ This model is evaluated at the [Chess Challenge Arena](https://huggingface.co/spaces/LLM-course/Chess1MChallenge).
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoConfig": "model.ChessConfig",
4
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
5
+ },
6
+ "architectures": [
7
+ "ChessForCausalLM"
8
+ ],
9
+ "bos_token_id": 1,
10
+ "dropout": 0.1,
11
+ "dtype": "float32",
12
+ "eos_token_id": 2,
13
+ "layer_norm_epsilon": 1e-05,
14
+ "model_type": "chess_transformer",
15
+ "n_ctx": 256,
16
+ "n_embd": 120,
17
+ "n_head": 4,
18
+ "n_inner": 480,
19
+ "n_layer": 4,
20
+ "pad_token_id": 0,
21
+ "tie_weights": true,
22
+ "transformers_version": "4.57.6",
23
+ "vocab_size": 83
24
+ }
data.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data loading utilities for the Chess Challenge.
3
+
4
+ This module provides functions to load and process chess game data
5
+ from the Lichess dataset on Hugging Face.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Dict, Iterator, List, Optional
11
+
12
+ import torch
13
+ from torch.utils.data import Dataset
14
+
15
+
16
+ class ChessDataset(Dataset):
17
+ """
18
+ PyTorch Dataset for chess games.
19
+
20
+ This dataset loads games from a Hugging Face dataset and prepares
21
+ them for language modeling training.
22
+
23
+ Each game is tokenized and truncated/padded to max_length.
24
+ The labels are shifted by one position for next-token prediction.
25
+
26
+ Example:
27
+ >>> from src.tokenizer import ChessTokenizer
28
+ >>> tokenizer = ChessTokenizer.build_vocab_from_dataset()
29
+ >>> dataset = ChessDataset(tokenizer, max_length=256)
30
+ >>> sample = dataset[0]
31
+ >>> print(sample["input_ids"].shape) # (256,)
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ tokenizer,
37
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
38
+ split: str = "train",
39
+ column: str = "text",
40
+ max_length: int = 256,
41
+ max_samples: Optional[int] = None,
42
+ ):
43
+ """
44
+ Initialize the chess dataset.
45
+
46
+ Args:
47
+ tokenizer: The chess tokenizer to use.
48
+ dataset_name: Name of the dataset on Hugging Face Hub.
49
+ split: Dataset split to use.
50
+ column: Column containing the game strings.
51
+ max_length: Maximum sequence length.
52
+ max_samples: Maximum number of samples to load.
53
+ """
54
+ from datasets import load_dataset
55
+
56
+ self.tokenizer = tokenizer
57
+ self.max_length = max_length
58
+ self.column = column
59
+
60
+ # Load dataset
61
+ dataset = load_dataset(dataset_name, split=split)
62
+
63
+ if max_samples is not None:
64
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
65
+
66
+ self.data = dataset
67
+
68
+ def __len__(self) -> int:
69
+ return len(self.data)
70
+
71
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
72
+ game = self.data[idx][self.column]
73
+
74
+ # Prepend BOS token for proper language modeling
75
+ game_with_bos = self.tokenizer.bos_token + " " + game
76
+
77
+ # Tokenize
78
+ encoding = self.tokenizer(
79
+ game_with_bos,
80
+ truncation=True,
81
+ max_length=self.max_length,
82
+ padding="max_length",
83
+ return_tensors="pt",
84
+ )
85
+
86
+ # Squeeze batch dimension
87
+ input_ids = encoding["input_ids"].squeeze(0)
88
+ attention_mask = encoding["attention_mask"].squeeze(0)
89
+
90
+ # Labels are the same as input_ids (model will shift internally)
91
+ labels = input_ids.clone()
92
+
93
+ # Set padding tokens to -100 to ignore in loss
94
+ labels[attention_mask == 0] = -100
95
+
96
+ return {
97
+ "input_ids": input_ids,
98
+ "attention_mask": attention_mask,
99
+ "labels": labels,
100
+ }
101
+
102
+
103
+ class ChessDataCollator:
104
+ """
105
+ Data collator for chess games.
106
+
107
+ This collator pads sequences to the same length within a batch
108
+ and creates the appropriate attention masks.
109
+ """
110
+
111
+ def __init__(self, tokenizer, max_length: int = 256):
112
+ self.tokenizer = tokenizer
113
+ self.max_length = max_length
114
+
115
+ def __call__(self, features: List[Dict]) -> Dict[str, torch.Tensor]:
116
+ # Stack tensors
117
+ input_ids = torch.stack([f["input_ids"] for f in features])
118
+ attention_mask = torch.stack([f["attention_mask"] for f in features])
119
+ labels = torch.stack([f["labels"] for f in features])
120
+
121
+ return {
122
+ "input_ids": input_ids,
123
+ "attention_mask": attention_mask,
124
+ "labels": labels,
125
+ }
126
+
127
+
128
+ def create_train_val_datasets(
129
+ tokenizer,
130
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
131
+ max_length: int = 256,
132
+ train_samples: Optional[int] = None,
133
+ val_samples: int = 5000,
134
+ val_ratio: float = 0.05,
135
+ ):
136
+ """
137
+ Create training and validation datasets.
138
+
139
+ Args:
140
+ tokenizer: The chess tokenizer.
141
+ dataset_name: Name of the dataset.
142
+ max_length: Maximum sequence length.
143
+ train_samples: Maximum training samples (None for all).
144
+ val_samples: Number of validation samples.
145
+ val_ratio: Ratio of validation samples (used if train_samples is None).
146
+
147
+ Returns:
148
+ Tuple of (train_dataset, val_dataset).
149
+ """
150
+ from datasets import load_dataset
151
+
152
+ # Load full dataset
153
+ full_dataset = load_dataset(dataset_name, split="train")
154
+
155
+ # Determine split sizes
156
+ total = len(full_dataset)
157
+
158
+ if train_samples is not None:
159
+ n_train = min(train_samples, total - val_samples)
160
+ else:
161
+ n_train = int(total * (1 - val_ratio))
162
+
163
+ n_val = min(val_samples, total - n_train)
164
+
165
+ # Split dataset
166
+ train_data = full_dataset.select(range(n_train))
167
+ val_data = full_dataset.select(range(n_train, n_train + n_val))
168
+
169
+ # Create dataset objects
170
+ train_dataset = ChessDataset(
171
+ tokenizer=tokenizer,
172
+ dataset_name=dataset_name,
173
+ max_length=max_length,
174
+ )
175
+ train_dataset.data = train_data
176
+
177
+ val_dataset = ChessDataset(
178
+ tokenizer=tokenizer,
179
+ dataset_name=dataset_name,
180
+ max_length=max_length,
181
+ )
182
+ val_dataset.data = val_data
183
+
184
+ return train_dataset, val_dataset
185
+
186
+
187
+ def stream_games(
188
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
189
+ split: str = "train",
190
+ column: str = "text",
191
+ ) -> Iterator[str]:
192
+ """
193
+ Stream games from the dataset for memory-efficient processing.
194
+
195
+ Args:
196
+ dataset_name: Name of the dataset on Hugging Face Hub.
197
+ split: Dataset split to use.
198
+ column: Column containing the game strings.
199
+
200
+ Yields:
201
+ Game strings one at a time.
202
+ """
203
+ from datasets import load_dataset
204
+
205
+ dataset = load_dataset(dataset_name, split=split, streaming=True)
206
+
207
+ for example in dataset:
208
+ yield example[column]
209
+
210
+
211
+ def analyze_dataset_statistics(
212
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
213
+ max_samples: int = 10000,
214
+ ) -> Dict:
215
+ """
216
+ Analyze statistics of the chess dataset.
217
+
218
+ Args:
219
+ dataset_name: Name of the dataset.
220
+ max_samples: Maximum number of samples to analyze.
221
+
222
+ Returns:
223
+ Dictionary containing dataset statistics.
224
+ """
225
+ from collections import Counter
226
+ from datasets import load_dataset
227
+
228
+ dataset = load_dataset(dataset_name, split="train")
229
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
230
+
231
+ game_lengths = []
232
+ move_counts = Counter()
233
+ opening_moves = Counter()
234
+
235
+ for example in dataset:
236
+ moves = example["text"].strip().split()
237
+ game_lengths.append(len(moves))
238
+ move_counts.update(moves)
239
+
240
+ # Track common openings (first 4 moves)
241
+ if len(moves) >= 4:
242
+ opening = " ".join(moves[:4])
243
+ opening_moves[opening] += 1
244
+
245
+ return {
246
+ "total_games": len(dataset),
247
+ "avg_game_length": sum(game_lengths) / len(game_lengths),
248
+ "min_game_length": min(game_lengths),
249
+ "max_game_length": max(game_lengths),
250
+ "unique_moves": len(move_counts),
251
+ "most_common_moves": move_counts.most_common(20),
252
+ "most_common_openings": opening_moves.most_common(10),
253
+ }
model.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chess Transformer Model for the Chess Challenge.
3
+
4
+ This module provides a simple GPT-style transformer architecture
5
+ designed to fit within the 1M parameter constraint.
6
+
7
+ Key components:
8
+ - ChessConfig: Configuration class for model hyperparameters
9
+ - ChessForCausalLM: The main model class for next-move prediction
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ from dataclasses import dataclass
16
+ from typing import Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers import PretrainedConfig, PreTrainedModel
22
+ from transformers.modeling_outputs import CausalLMOutputWithPast
23
+
24
+
25
+ class ChessConfig(PretrainedConfig):
26
+ """
27
+ Configuration class for the Chess Transformer model.
28
+
29
+ This configuration is designed for a ~1M parameter model.
30
+ Students can adjust these values to explore different architectures.
31
+
32
+ Parameter budget breakdown (with default values):
33
+ - Embeddings (vocab): 1200 x 128 = 153,600
34
+ - Position Embeddings: 256 x 128 = 32,768
35
+ - Transformer Layers: 6 x ~120,000 = ~720,000
36
+ - LM Head (with weight tying): 0 (shared with embeddings)
37
+ - Total: ~906,000 parameters
38
+
39
+ Attributes:
40
+ vocab_size: Size of the vocabulary (number of unique moves).
41
+ n_embd: Embedding dimension (d_model).
42
+ n_layer: Number of transformer layers.
43
+ n_head: Number of attention heads.
44
+ n_ctx: Maximum sequence length (context window).
45
+ n_inner: Feed-forward inner dimension (default: 3 * n_embd).
46
+ dropout: Dropout probability.
47
+ layer_norm_epsilon: Epsilon for layer normalization.
48
+ tie_weights: Whether to tie embedding and output weights.
49
+ """
50
+
51
+ model_type = "chess_transformer"
52
+
53
+ def __init__(
54
+ self,
55
+ vocab_size: int = 1200,
56
+ n_embd: int = 128,
57
+ n_layer: int = 6,
58
+ n_head: int = 4,
59
+ n_ctx: int = 256,
60
+ n_inner: Optional[int] = None,
61
+ dropout: float = 0.1,
62
+ layer_norm_epsilon: float = 1e-5,
63
+ tie_weights: bool = True,
64
+ pad_token_id: int = 0,
65
+ bos_token_id: int = 1,
66
+ eos_token_id: int = 2,
67
+ **kwargs,
68
+ ):
69
+ super().__init__(
70
+ pad_token_id=pad_token_id,
71
+ bos_token_id=bos_token_id,
72
+ eos_token_id=eos_token_id,
73
+ **kwargs,
74
+ )
75
+
76
+ self.vocab_size = vocab_size
77
+ self.n_embd = n_embd
78
+ self.n_layer = n_layer
79
+ self.n_head = n_head
80
+ self.n_ctx = n_ctx
81
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
82
+ self.dropout = dropout
83
+ self.layer_norm_epsilon = layer_norm_epsilon
84
+ self.tie_weights = tie_weights
85
+ # Inform HF base class about tying behavior
86
+ self.tie_word_embeddings = bool(tie_weights)
87
+
88
+
89
+ class MultiHeadAttention(nn.Module):
90
+ """
91
+ Multi-head self-attention module.
92
+
93
+ This is a standard scaled dot-product attention implementation
94
+ with causal masking for autoregressive generation.
95
+ """
96
+
97
+ def __init__(self, config: ChessConfig):
98
+ super().__init__()
99
+
100
+ assert config.n_embd % config.n_head == 0, \
101
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
102
+
103
+ self.n_head = config.n_head
104
+ self.n_embd = config.n_embd
105
+ self.head_dim = config.n_embd // config.n_head
106
+
107
+ # Combined QKV projection for efficiency
108
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
109
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
110
+
111
+ self.dropout = nn.Dropout(config.dropout)
112
+
113
+ # Causal mask (will be created on first forward pass)
114
+ self.register_buffer(
115
+ "bias",
116
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
117
+ 1, 1, config.n_ctx, config.n_ctx
118
+ ),
119
+ persistent=False,
120
+ )
121
+
122
+ def forward(
123
+ self,
124
+ x: torch.Tensor,
125
+ attention_mask: Optional[torch.Tensor] = None,
126
+ ) -> torch.Tensor:
127
+ batch_size, seq_len, _ = x.size()
128
+
129
+ # Compute Q, K, V
130
+ qkv = self.c_attn(x)
131
+ q, k, v = qkv.split(self.n_embd, dim=2)
132
+
133
+ # Reshape for multi-head attention
134
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
135
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
136
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
137
+
138
+ # Scaled dot-product attention
139
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
140
+
141
+ # Apply causal mask
142
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
143
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
144
+
145
+ # Apply attention mask (for padding)
146
+ if attention_mask is not None:
147
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
148
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
149
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
150
+
151
+ attn_weights = F.softmax(attn_weights, dim=-1)
152
+ attn_weights = self.dropout(attn_weights)
153
+
154
+ # Apply attention to values
155
+ attn_output = torch.matmul(attn_weights, v)
156
+
157
+ # Reshape back
158
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
159
+ batch_size, seq_len, self.n_embd
160
+ )
161
+
162
+ # Output projection
163
+ attn_output = self.c_proj(attn_output)
164
+
165
+ return attn_output
166
+
167
+
168
+ class FeedForward(nn.Module):
169
+ """
170
+ Feed-forward network (MLP) module.
171
+
172
+ Standard two-layer MLP with GELU activation.
173
+ """
174
+
175
+ def __init__(self, config: ChessConfig):
176
+ super().__init__()
177
+
178
+ self.c_fc = nn.Linear(config.n_embd, config.n_inner)
179
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
180
+ self.dropout = nn.Dropout(config.dropout)
181
+
182
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
183
+ x = self.c_fc(x)
184
+ x = F.gelu(x)
185
+ x = self.c_proj(x)
186
+ x = self.dropout(x)
187
+ return x
188
+
189
+
190
+ class TransformerBlock(nn.Module):
191
+ """
192
+ A single transformer block with attention and feed-forward layers.
193
+
194
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
195
+ training stability.
196
+ """
197
+
198
+ def __init__(self, config: ChessConfig):
199
+ super().__init__()
200
+
201
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
202
+ self.attn = MultiHeadAttention(config)
203
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
204
+ self.mlp = FeedForward(config)
205
+
206
+ def forward(
207
+ self,
208
+ x: torch.Tensor,
209
+ attention_mask: Optional[torch.Tensor] = None,
210
+ ) -> torch.Tensor:
211
+ # Pre-norm attention
212
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
213
+ # Pre-norm FFN
214
+ x = x + self.mlp(self.ln_2(x))
215
+ return x
216
+
217
+
218
+ class ChessForCausalLM(PreTrainedModel):
219
+ """
220
+ Chess Transformer for Causal Language Modeling (next-move prediction).
221
+
222
+ This model is designed to predict the next chess move given a sequence
223
+ of previous moves. It uses a GPT-style architecture with:
224
+ - Token embeddings for chess moves
225
+ - Learned positional embeddings
226
+ - Stacked transformer blocks
227
+ - Linear head for next-token prediction
228
+
229
+ The model supports weight tying between the embedding layer and the
230
+ output projection to save parameters.
231
+
232
+ Example:
233
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
234
+ >>> model = ChessForCausalLM(config)
235
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
236
+ >>> outputs = model(**inputs)
237
+ >>> next_move_logits = outputs.logits[:, -1, :]
238
+ """
239
+
240
+ config_class = ChessConfig
241
+ base_model_prefix = "transformer"
242
+ supports_gradient_checkpointing = True
243
+ # Suppress missing-key warning for tied lm_head when loading
244
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
245
+
246
+ def __init__(self, config: ChessConfig):
247
+ super().__init__(config)
248
+
249
+ # Token and position embeddings
250
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
251
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
252
+
253
+ self.drop = nn.Dropout(config.dropout)
254
+
255
+ # Transformer blocks
256
+ self.h = nn.ModuleList([
257
+ TransformerBlock(config) for _ in range(config.n_layer)
258
+ ])
259
+
260
+ # Final layer norm
261
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
262
+
263
+ # Output head
264
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
265
+
266
+ # Declare tied weights for proper serialization
267
+ if config.tie_weights:
268
+ self._tied_weights_keys = ["lm_head.weight"]
269
+
270
+ # Initialize weights
271
+ self.post_init()
272
+
273
+ # Tie weights if configured
274
+ if config.tie_weights:
275
+ self.tie_weights()
276
+
277
+ def get_input_embeddings(self) -> nn.Module:
278
+ return self.wte
279
+
280
+ def set_input_embeddings(self, new_embeddings: nn.Module):
281
+ self.wte = new_embeddings
282
+ if getattr(self.config, "tie_weights", False):
283
+ self.tie_weights()
284
+
285
+ def get_output_embeddings(self) -> nn.Module:
286
+ return self.lm_head
287
+
288
+ def set_output_embeddings(self, new_embeddings: nn.Module):
289
+ self.lm_head = new_embeddings
290
+
291
+ def tie_weights(self):
292
+ # Use HF helper to tie or clone depending on config
293
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
294
+ self._tie_or_clone_weights(self.lm_head, self.wte)
295
+
296
+ def _init_weights(self, module: nn.Module):
297
+ """Initialize weights following GPT-2 style."""
298
+ if isinstance(module, nn.Linear):
299
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
300
+ if module.bias is not None:
301
+ torch.nn.init.zeros_(module.bias)
302
+ elif isinstance(module, nn.Embedding):
303
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
304
+ elif isinstance(module, nn.LayerNorm):
305
+ torch.nn.init.ones_(module.weight)
306
+ torch.nn.init.zeros_(module.bias)
307
+
308
+ def forward(
309
+ self,
310
+ input_ids: torch.LongTensor,
311
+ attention_mask: Optional[torch.Tensor] = None,
312
+ position_ids: Optional[torch.LongTensor] = None,
313
+ labels: Optional[torch.LongTensor] = None,
314
+ return_dict: Optional[bool] = None,
315
+ **kwargs,
316
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
317
+ """
318
+ Forward pass of the model.
319
+
320
+ Args:
321
+ input_ids: Token IDs of shape (batch_size, seq_len).
322
+ attention_mask: Attention mask of shape (batch_size, seq_len).
323
+ position_ids: Position IDs of shape (batch_size, seq_len).
324
+ labels: Labels for language modeling loss.
325
+ return_dict: Whether to return a ModelOutput object.
326
+
327
+ Returns:
328
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
329
+ """
330
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
331
+
332
+ batch_size, seq_len = input_ids.size()
333
+ device = input_ids.device
334
+
335
+ # Create position IDs if not provided
336
+ if position_ids is None:
337
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
338
+
339
+ # Get embeddings
340
+ token_embeds = self.wte(input_ids)
341
+ position_embeds = self.wpe(position_ids)
342
+ hidden_states = self.drop(token_embeds + position_embeds)
343
+
344
+ # Pass through transformer blocks
345
+ for block in self.h:
346
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
347
+
348
+ # Final layer norm
349
+ hidden_states = self.ln_f(hidden_states)
350
+
351
+ # Get logits
352
+ logits = self.lm_head(hidden_states)
353
+
354
+ # Compute loss if labels are provided
355
+ loss = None
356
+ if labels is not None:
357
+ # Shift logits and labels for next-token prediction
358
+ shift_logits = logits[..., :-1, :].contiguous()
359
+ shift_labels = labels[..., 1:].contiguous()
360
+
361
+ # Flatten for cross-entropy
362
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
363
+ # loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
364
+ loss = loss_fct(
365
+ shift_logits.view(-1, shift_logits.size(-1)),
366
+ shift_labels.view(-1),
367
+ )
368
+
369
+ if not return_dict:
370
+ output = (logits,)
371
+ return ((loss,) + output) if loss is not None else output
372
+
373
+ return CausalLMOutputWithPast(
374
+ loss=loss,
375
+ logits=logits,
376
+ past_key_values=None,
377
+ hidden_states=None,
378
+ attentions=None,
379
+ )
380
+
381
+ @torch.no_grad()
382
+ def generate_move(
383
+ self,
384
+ input_ids: torch.LongTensor,
385
+ temperature: float = 1.0,
386
+ top_k: Optional[int] = None,
387
+ top_p: Optional[float] = None,
388
+ ) -> int:
389
+ """
390
+ Generate the next move given a sequence of moves.
391
+
392
+ Args:
393
+ input_ids: Token IDs of shape (1, seq_len).
394
+ temperature: Sampling temperature (1.0 = no change).
395
+ top_k: If set, only sample from top k tokens.
396
+ top_p: If set, use nucleus sampling with this threshold.
397
+
398
+ Returns:
399
+ The token ID of the predicted next move.
400
+ """
401
+ self.eval()
402
+
403
+ # Get logits for the last position
404
+ outputs = self(input_ids)
405
+ logits = outputs.logits[:, -1, :] / temperature
406
+
407
+ # Apply top-k filtering
408
+ if top_k is not None:
409
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
410
+ logits[indices_to_remove] = float("-inf")
411
+
412
+ # Apply top-p (nucleus) filtering
413
+ if top_p is not None:
414
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
415
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
416
+
417
+ # Remove tokens with cumulative probability above the threshold
418
+ sorted_indices_to_remove = cumulative_probs > top_p
419
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
420
+ sorted_indices_to_remove[..., 0] = 0
421
+
422
+ indices_to_remove = sorted_indices_to_remove.scatter(
423
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
424
+ )
425
+ logits[indices_to_remove] = float("-inf")
426
+
427
+ # Sample from the distribution
428
+ probs = F.softmax(logits, dim=-1)
429
+ next_token = torch.multinomial(probs, num_samples=1)
430
+
431
+ return next_token.item()
432
+
433
+
434
+ # Register the model with Auto classes for easy loading
435
+ from transformers import AutoConfig, AutoModelForCausalLM
436
+
437
+ AutoConfig.register("chess_transformer", ChessConfig)
438
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8de0af4b0f13d2a81c8fa50f28bd6718b3d44f685324ece2ef2e70cfa80bd521
3
+ size 2957840
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,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ This tokenizer uses sub-structural tokenization: each move is decomposed into
5
+ its components (piece, source square, destination square, suffix) instead of
6
+ treating the whole move as a single token.
7
+
8
+ Example: WPe2e4 -> [P, e2, e4] (color is implicit from move number)
9
+ BNg8f6(x) -> [N, g8, f6, (x)]
10
+
11
+ This approach:
12
+ - Reduces vocabulary from ~1200 to ~80 tokens
13
+ - Enables generalization across similar moves
14
+ - Eliminates [UNK] tokens for rare moves
15
+ - Saves parameters in the embedding layer
16
+
17
+ The dataset format uses:
18
+ - W/B prefix for White/Black (ignored - implicit from position)
19
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
20
+ - Source and destination squares (e.g., e2e4)
21
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import re
29
+ from pathlib import Path
30
+ from typing import Dict, List, Optional, Tuple
31
+
32
+ from transformers import PreTrainedTokenizer
33
+
34
+
35
+ # Regex pattern to parse extended UCI notation
36
+ # Matches: (W|B)(Piece)(src_file)(src_rank)(dst_file)(dst_rank)(suffix?)
37
+ MOVE_PATTERN = re.compile(
38
+ r'^([WB])([PNBRQK])([a-h])([1-8])([a-h])([1-8])(\([^)]+\))?$'
39
+ )
40
+
41
+
42
+ class ChessTokenizer(PreTrainedTokenizer):
43
+ """
44
+ A custom tokenizer for chess moves using sub-structural tokenization.
45
+
46
+ Each move is decomposed into components:
47
+ - Piece type (P, N, B, R, Q, K)
48
+ - Source square (e2, d7, etc.)
49
+ - Destination square (e4, f6, etc.)
50
+ - Optional suffix for captures/checks ((x), (+), (+*), (o), (O))
51
+
52
+ The color (W/B) is NOT tokenized as it's implicit from the move order.
53
+
54
+ Example:
55
+ >>> tokenizer = ChessTokenizer.build_vocab()
56
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
57
+ [1, 5, 20, 28, 5, 52, 44, 2] # [BOS, P, e2, e4, P, e7, e5, EOS]
58
+ """
59
+
60
+ model_input_names = ["input_ids", "attention_mask"]
61
+ vocab_files_names = {"vocab_file": "vocab.json"}
62
+
63
+ # Special tokens
64
+ PAD_TOKEN = "[PAD]"
65
+ BOS_TOKEN = "[BOS]"
66
+ EOS_TOKEN = "[EOS]"
67
+ UNK_TOKEN = "[UNK]"
68
+
69
+ def __init__(
70
+ self,
71
+ vocab_file: Optional[str] = None,
72
+ vocab: Optional[Dict[str, int]] = None,
73
+ **kwargs,
74
+ ):
75
+ """
76
+ Initialize the chess tokenizer.
77
+
78
+ Args:
79
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
80
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
81
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
82
+ """
83
+ # Initialize special tokens
84
+ self._pad_token = self.PAD_TOKEN
85
+ self._bos_token = self.BOS_TOKEN
86
+ self._eos_token = self.EOS_TOKEN
87
+ self._unk_token = self.UNK_TOKEN
88
+
89
+ # Remove any duplicate special-token entries passed through kwargs
90
+ # to avoid "multiple values for keyword" errors when loading from disk.
91
+ kwargs.pop("pad_token", None)
92
+ kwargs.pop("bos_token", None)
93
+ kwargs.pop("eos_token", None)
94
+ kwargs.pop("unk_token", None)
95
+
96
+ # Load or create vocabulary
97
+ if vocab is not None:
98
+ self._vocab = vocab
99
+ elif vocab_file is not None and os.path.exists(vocab_file):
100
+ with open(vocab_file, "r", encoding="utf-8") as f:
101
+ self._vocab = json.load(f)
102
+ else:
103
+ # Create a minimal vocabulary with just special tokens
104
+ # The full vocabulary should be built from the dataset
105
+ self._vocab = self._create_default_vocab()
106
+
107
+ # Create reverse mapping
108
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
109
+
110
+ # Call parent init AFTER setting up vocab
111
+ super().__init__(
112
+ pad_token=self._pad_token,
113
+ bos_token=self._bos_token,
114
+ eos_token=self._eos_token,
115
+ unk_token=self._unk_token,
116
+ **kwargs,
117
+ )
118
+
119
+ def _create_default_vocab(self) -> Dict[str, int]:
120
+ """
121
+ Create the full sub-structural vocabulary.
122
+
123
+ The vocabulary contains:
124
+ - 4 special tokens: [PAD], [BOS], [EOS], [UNK]
125
+ - 6 piece tokens: P, N, B, R, Q, K
126
+ - 64 square tokens: a1, a2, ..., h8
127
+ - 5 suffix tokens: (x), (+), (+*), (o), (O)
128
+
129
+ Total: 79 tokens (vs ~1200 for move-level tokenization)
130
+ """
131
+ tokens = []
132
+
133
+ # Special tokens first
134
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
135
+ tokens.extend(special_tokens)
136
+
137
+ # Piece tokens
138
+ pieces = ['P', 'N', 'B', 'R', 'Q', 'K']
139
+ tokens.extend(pieces)
140
+
141
+ # Square tokens (a1-h8)
142
+ files = 'abcdefgh'
143
+ ranks = '12345678'
144
+ for f in files:
145
+ for r in ranks:
146
+ tokens.append(f + r)
147
+
148
+ # Suffix tokens for special moves
149
+ suffixes = ['(x)', '(+)', '(+*)', '(o)', '(O)']
150
+ tokens.extend(suffixes)
151
+
152
+ # Promotion tokens (pawn promotion to piece)
153
+ # Format in dataset might be like WPe7e8Q for promotion
154
+ promotion_pieces = ['=Q', '=R', '=B', '=N']
155
+ tokens.extend(promotion_pieces)
156
+
157
+ vocab = {token: idx for idx, token in enumerate(tokens)}
158
+ return vocab
159
+
160
+ @classmethod
161
+ def build_vocab(cls) -> "ChessTokenizer":
162
+ """
163
+ Build a tokenizer with the pre-defined sub-structural vocabulary.
164
+
165
+ This is the recommended way to create a tokenizer for the chess challenge.
166
+ The vocabulary is deterministic and covers all possible moves.
167
+
168
+ Returns:
169
+ A ChessTokenizer with the full sub-structural vocabulary (~83 tokens).
170
+ """
171
+ return cls()
172
+
173
+ @classmethod
174
+ def build_vocab_from_iterator(
175
+ cls,
176
+ iterator,
177
+ min_frequency: int = 1,
178
+ ) -> "ChessTokenizer":
179
+ """
180
+ Build a tokenizer vocabulary from an iterator of game strings.
181
+
182
+ Note: With sub-structural tokenization, this method is mainly useful
183
+ for analyzing token frequencies. The default vocabulary already covers
184
+ all possible moves.
185
+
186
+ Args:
187
+ iterator: An iterator yielding game strings (space-separated moves).
188
+ min_frequency: Minimum frequency for a token to be included.
189
+
190
+ Returns:
191
+ A ChessTokenizer with the built vocabulary.
192
+ """
193
+ # With sub-structural tokenization, we use the default vocab
194
+ # which already contains all possible sub-tokens
195
+ return cls()
196
+
197
+ @classmethod
198
+ def build_vocab_from_dataset(
199
+ cls,
200
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
201
+ split: str = "train",
202
+ column: str = "text",
203
+ min_frequency: int = 500,
204
+ max_samples: Optional[int] = 100000,
205
+ ) -> "ChessTokenizer":
206
+ """
207
+ Build a tokenizer vocabulary from a Hugging Face dataset.
208
+
209
+ Note: With sub-structural tokenization, the vocabulary is pre-defined
210
+ and doesn't need to be built from data. This method is kept for
211
+ compatibility but simply returns a tokenizer with the default vocab.
212
+
213
+ Args:
214
+ dataset_name: Name of the dataset on Hugging Face Hub.
215
+ split: Dataset split to use.
216
+ column: Column containing the game strings.
217
+ min_frequency: Minimum frequency for a token to be included.
218
+ max_samples: Maximum number of samples to process.
219
+
220
+ Returns:
221
+ A ChessTokenizer with the full sub-structural vocabulary.
222
+ """
223
+ # With sub-structural tokenization, we don't need to scan the dataset
224
+ return cls()
225
+
226
+ @property
227
+ def vocab_size(self) -> int:
228
+ """Return the size of the vocabulary."""
229
+ return len(self._vocab)
230
+
231
+ def get_vocab(self) -> Dict[str, int]:
232
+ """Return the vocabulary as a dictionary."""
233
+ return dict(self._vocab)
234
+
235
+ def _parse_move(self, move: str) -> List[str]:
236
+ """
237
+ Parse a single move into its sub-components.
238
+
239
+ Args:
240
+ move: A move in extended UCI notation (e.g., WPe2e4, BNg8f6(x))
241
+
242
+ Returns:
243
+ List of tokens: [piece, src_square, dst_square, suffix?]
244
+ Color (W/B) is ignored as it's implicit from move order.
245
+ """
246
+ # Try standard move pattern
247
+ match = MOVE_PATTERN.match(move)
248
+ if match:
249
+ color, piece, src_file, src_rank, dst_file, dst_rank, suffix = match.groups()
250
+ tokens = [piece, src_file + src_rank, dst_file + dst_rank]
251
+ if suffix:
252
+ tokens.append(suffix)
253
+ return tokens
254
+
255
+ # Try promotion pattern: WPe7e8Q or WPe7e8Q(+)
256
+ promo_pattern = re.match(
257
+ r'^([WB])P([a-h])([1-8])([a-h])([1-8])([QRBN])(\([^)]+\))?$',
258
+ move
259
+ )
260
+ if promo_pattern:
261
+ color, src_file, src_rank, dst_file, dst_rank, promo_piece, suffix = promo_pattern.groups()
262
+ tokens = ['P', src_file + src_rank, dst_file + dst_rank, '=' + promo_piece]
263
+ if suffix:
264
+ tokens.append(suffix)
265
+ return tokens
266
+
267
+ # Fallback: return as single token (will likely be UNK)
268
+ return [move]
269
+
270
+ def _tokenize(self, text: str) -> List[str]:
271
+ """
272
+ Tokenize a string of moves into sub-structural tokens.
273
+
274
+ Each move is decomposed into:
275
+ - Piece type (P, N, B, R, Q, K)
276
+ - Source square (e2, d7, etc.)
277
+ - Destination square (e4, f6, etc.)
278
+ - Optional suffix ((x), (+), etc.)
279
+
280
+ Args:
281
+ text: A string of space-separated moves.
282
+
283
+ Returns:
284
+ List of sub-tokens.
285
+
286
+ Example:
287
+ "WPe2e4 BPe7e5" -> ['P', 'e2', 'e4', 'P', 'e7', 'e5']
288
+ """
289
+ tokens = []
290
+ moves = text.strip().split()
291
+ for move in moves:
292
+ tokens.extend(self._parse_move(move))
293
+ return tokens
294
+
295
+ def _convert_token_to_id(self, token: str) -> int:
296
+ """Convert a token to its ID."""
297
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
298
+
299
+ def _convert_id_to_token(self, index: int) -> str:
300
+ """Convert an ID to its token."""
301
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
302
+
303
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
304
+ """
305
+ Convert a list of sub-tokens back to a string of moves.
306
+
307
+ Reconstructs moves from their components. Each move consists of:
308
+ - Piece token (P, N, B, R, Q, K)
309
+ - Source square (e2, d7, etc.)
310
+ - Destination square (e4, f6, etc.)
311
+ - Optional suffix ((x), (+), etc.) or promotion (=Q, =R, etc.)
312
+
313
+ Args:
314
+ tokens: List of sub-tokens.
315
+
316
+ Returns:
317
+ Space-separated string of reconstructed moves.
318
+ """
319
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
320
+ pieces = {'P', 'N', 'B', 'R', 'Q', 'K'}
321
+ suffixes = {'(x)', '(+)', '(+*)', '(o)', '(O)'}
322
+ promotions = {'=Q', '=R', '=B', '=N'}
323
+
324
+ moves = []
325
+ current_move = []
326
+
327
+ for token in tokens:
328
+ if token in special:
329
+ continue
330
+
331
+ if token in pieces:
332
+ # Start of a new move - save previous if exists
333
+ if current_move:
334
+ moves.append(''.join(current_move))
335
+ current_move = [token]
336
+ elif token in suffixes or token in promotions:
337
+ # End of move with suffix/promotion
338
+ current_move.append(token)
339
+ else:
340
+ # Square token
341
+ current_move.append(token)
342
+
343
+ # Don't forget the last move
344
+ if current_move:
345
+ moves.append(''.join(current_move))
346
+
347
+ return " ".join(moves)
348
+
349
+ def save_vocabulary(
350
+ self,
351
+ save_directory: str,
352
+ filename_prefix: Optional[str] = None,
353
+ ) -> tuple:
354
+ """
355
+ Save the vocabulary to a JSON file.
356
+
357
+ Args:
358
+ save_directory: Directory to save the vocabulary.
359
+ filename_prefix: Optional prefix for the filename.
360
+
361
+ Returns:
362
+ Tuple containing the path to the saved vocabulary file.
363
+ """
364
+ if not os.path.isdir(save_directory):
365
+ os.makedirs(save_directory, exist_ok=True)
366
+
367
+ vocab_file = os.path.join(
368
+ save_directory,
369
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
370
+ )
371
+
372
+ with open(vocab_file, "w", encoding="utf-8") as f:
373
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
374
+
375
+ return (vocab_file,)
376
+
377
+
378
+ def count_vocab_from_dataset(
379
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
380
+ split: str = "train",
381
+ column: str = "text",
382
+ max_samples: Optional[int] = 10000,
383
+ ) -> Dict[str, int]:
384
+ """
385
+ Count sub-token frequencies in a dataset (useful for vocabulary analysis).
386
+
387
+ Args:
388
+ dataset_name: Name of the dataset on Hugging Face Hub.
389
+ split: Dataset split to use.
390
+ column: Column containing the game strings.
391
+ max_samples: Maximum number of samples to process.
392
+
393
+ Returns:
394
+ Dictionary mapping sub-tokens to their frequencies.
395
+ """
396
+ from collections import Counter
397
+ from datasets import load_dataset
398
+
399
+ dataset = load_dataset(dataset_name, split=split)
400
+
401
+ if max_samples is not None:
402
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
403
+
404
+ # Use a tokenizer instance to parse moves into sub-tokens
405
+ tokenizer = ChessTokenizer()
406
+ token_counts = Counter()
407
+
408
+ for example in dataset:
409
+ sub_tokens = tokenizer._tokenize(example[column])
410
+ token_counts.update(sub_tokens)
411
+
412
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": ["tokenizer.ChessTokenizer", "tokenizer.ChessTokenizer"]
4
+ },
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "[PAD]",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "[BOS]",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "[EOS]",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "3": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ }
38
+ },
39
+ "bos_token": "[BOS]",
40
+ "clean_up_tokenization_spaces": false,
41
+ "eos_token": "[EOS]",
42
+ "extra_special_tokens": {},
43
+ "model_max_length": 1000000000000000019884624838656,
44
+ "pad_token": "[PAD]",
45
+ "tokenizer_class": "ChessTokenizer",
46
+ "unk_token": "[UNK]"
47
+ }
train.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for the Chess Challenge.
3
+
4
+ This script provides a complete training pipeline using the Hugging Face Trainer.
5
+ Students can modify this script to experiment with different training strategies.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import warnings
13
+ from pathlib import Path
14
+
15
+ # Suppress warnings from third-party libraries (multiprocess has Python 3.14 compat issues)
16
+ warnings.filterwarnings("ignore", message="'return' in a 'finally' block")
17
+
18
+ import torch
19
+ from transformers import (
20
+ Trainer,
21
+ TrainingArguments,
22
+ set_seed,
23
+ )
24
+
25
+ from src.data import ChessDataCollator, create_train_val_datasets
26
+ from src.model import ChessConfig, ChessForCausalLM
27
+ from src.tokenizer import ChessTokenizer
28
+ from src.utils import count_parameters, print_parameter_budget
29
+
30
+
31
+ def parse_args():
32
+ """Parse command line arguments."""
33
+ parser = argparse.ArgumentParser(
34
+ description="Train a chess-playing language model"
35
+ )
36
+
37
+ # Model arguments
38
+ parser.add_argument(
39
+ "--n_embd", type=int, default=128,
40
+ help="Embedding dimension"
41
+ )
42
+ parser.add_argument(
43
+ "--n_layer", type=int, default=4,
44
+ help="Number of transformer layers"
45
+ )
46
+ parser.add_argument(
47
+ "--n_head", type=int, default=4,
48
+ help="Number of attention heads"
49
+ )
50
+ parser.add_argument(
51
+ "--n_ctx", type=int, default=256,
52
+ help="Maximum context length"
53
+ )
54
+ parser.add_argument(
55
+ "--n_inner", type=int, default=None,
56
+ help="Feed-forward inner dimension (default: 4 * n_embd)"
57
+ )
58
+ parser.add_argument(
59
+ "--dropout", type=float, default=0.1,
60
+ help="Dropout probability"
61
+ )
62
+ parser.add_argument(
63
+ "--no_tie_weights", action="store_true",
64
+ help="Disable weight tying between embedding and output layers"
65
+ )
66
+
67
+ # Data arguments
68
+ parser.add_argument(
69
+ "--dataset_name", type=str, default="dlouapre/lichess_2025-01_1M",
70
+ help="Name of the dataset on Hugging Face Hub"
71
+ )
72
+ parser.add_argument(
73
+ "--max_train_samples", type=int, default=None,
74
+ help="Maximum number of training samples"
75
+ )
76
+ parser.add_argument(
77
+ "--val_samples", type=int, default=5000,
78
+ help="Number of validation samples"
79
+ )
80
+
81
+ # Training arguments
82
+ parser.add_argument(
83
+ "--output_dir", type=str, default="./output",
84
+ help="Output directory for model and logs"
85
+ )
86
+ parser.add_argument(
87
+ "--num_train_epochs", type=int, default=3,
88
+ help="Number of training epochs"
89
+ )
90
+ parser.add_argument(
91
+ "--per_device_train_batch_size", type=int, default=32,
92
+ help="Training batch size per device"
93
+ )
94
+ parser.add_argument(
95
+ "--per_device_eval_batch_size", type=int, default=64,
96
+ help="Evaluation batch size per device"
97
+ )
98
+ parser.add_argument(
99
+ "--learning_rate", type=float, default=5e-4,
100
+ help="Learning rate"
101
+ )
102
+ parser.add_argument(
103
+ "--weight_decay", type=float, default=0.01,
104
+ help="Weight decay"
105
+ )
106
+ parser.add_argument(
107
+ "--warmup_ratio", type=float, default=0.1,
108
+ help="Warmup ratio"
109
+ )
110
+ parser.add_argument(
111
+ "--seed", type=int, default=42,
112
+ help="Random seed"
113
+ )
114
+
115
+ # Logging arguments
116
+ parser.add_argument(
117
+ "--logging_steps", type=int, default=100,
118
+ help="Logging frequency"
119
+ )
120
+ parser.add_argument(
121
+ "--eval_steps", type=int, default=500,
122
+ help="Evaluation frequency"
123
+ )
124
+ parser.add_argument(
125
+ "--save_steps", type=int, default=1000,
126
+ help="Checkpoint saving frequency"
127
+ )
128
+
129
+ return parser.parse_args()
130
+
131
+
132
+ def main():
133
+ """Main training function."""
134
+ args = parse_args()
135
+
136
+ # Set seed for reproducibility
137
+ set_seed(args.seed)
138
+
139
+ print("=" * 60)
140
+ print("CHESS CHALLENGE - TRAINING")
141
+ print("=" * 60)
142
+
143
+ # Build tokenizer from dataset
144
+ print("\nBuilding tokenizer from dataset...")
145
+ tokenizer = ChessTokenizer.build_vocab_from_dataset(
146
+ dataset_name=args.dataset_name,
147
+ min_frequency=500, # Only keep moves that appear at least 500 times
148
+ max_samples=100000, # Use 100k games to build vocabulary
149
+ )
150
+ print(f" Vocabulary size: {tokenizer.vocab_size}")
151
+
152
+ # Use the vocab size from tokenizer (override args if provided)
153
+ actual_vocab_size = tokenizer.vocab_size
154
+
155
+ # Create model configuration
156
+ print("\nCreating model configuration...")
157
+ config = ChessConfig(
158
+ vocab_size=actual_vocab_size,
159
+ n_embd=args.n_embd,
160
+ n_layer=args.n_layer,
161
+ n_head=args.n_head,
162
+ n_ctx=args.n_ctx,
163
+ n_inner=args.n_inner,
164
+ dropout=args.dropout,
165
+ tie_weights=not args.no_tie_weights,
166
+ pad_token_id=tokenizer.pad_token_id,
167
+ bos_token_id=tokenizer.bos_token_id,
168
+ eos_token_id=tokenizer.eos_token_id,
169
+ )
170
+
171
+ # Print parameter budget
172
+ print_parameter_budget(config)
173
+
174
+ # Create model
175
+ print("\nCreating model...")
176
+ model = ChessForCausalLM(config)
177
+ n_params = count_parameters(model)
178
+ print(f" Total parameters: {n_params:,}")
179
+
180
+ if n_params > 1_000_000:
181
+ print("WARNING: Model exceeds 1M parameter limit!")
182
+ else:
183
+ print("✓ Model is within 1M parameter limit")
184
+
185
+ # Load datasets
186
+ print("\nLoading datasets...")
187
+ train_dataset, val_dataset = create_train_val_datasets(
188
+ tokenizer=tokenizer,
189
+ dataset_name=args.dataset_name,
190
+ max_length=args.n_ctx,
191
+ train_samples=args.max_train_samples,
192
+ val_samples=args.val_samples,
193
+ )
194
+ print(f" Training samples: {len(train_dataset):,}")
195
+ print(f" Validation samples: {len(val_dataset):,}")
196
+
197
+ # Create data collator
198
+ data_collator = ChessDataCollator(tokenizer, max_length=args.n_ctx)
199
+
200
+ # Training arguments
201
+ training_args = TrainingArguments(
202
+ output_dir=args.output_dir,
203
+ num_train_epochs=args.num_train_epochs,
204
+ per_device_train_batch_size=args.per_device_train_batch_size,
205
+ per_device_eval_batch_size=args.per_device_eval_batch_size,
206
+ learning_rate=args.learning_rate,
207
+ weight_decay=args.weight_decay,
208
+ warmup_ratio=args.warmup_ratio,
209
+ logging_dir=os.path.join(args.output_dir, "logs"),
210
+ logging_steps=args.logging_steps,
211
+ eval_strategy="epoch",
212
+ save_strategy="epoch",
213
+ save_total_limit=3,
214
+ load_best_model_at_end=True,
215
+ metric_for_best_model="eval_loss",
216
+ greater_is_better=False,
217
+ seed=args.seed,
218
+ bf16=torch.cuda.is_available() and torch.cuda.is_bf16_supported(),
219
+ report_to=["none"],
220
+ )
221
+
222
+ # Create trainer
223
+ trainer = Trainer(
224
+ model=model,
225
+ args=training_args,
226
+ train_dataset=train_dataset,
227
+ eval_dataset=val_dataset,
228
+ data_collator=data_collator,
229
+ tokenizer=tokenizer,
230
+ )
231
+
232
+ # Train
233
+ print("\nStarting training...")
234
+ trainer.train()
235
+
236
+ # Save final model
237
+ print("\nSaving final model...")
238
+ trainer.save_model(os.path.join(args.output_dir, "final_model"))
239
+ tokenizer.save_pretrained(os.path.join(args.output_dir, "final_model"))
240
+
241
+ print("\nTraining complete!")
242
+ print(f" Model saved to: {args.output_dir}/final_model")
243
+
244
+
245
+ if __name__ == "__main__":
246
+ main()
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa7ce3ac54313022aeae40b97dffd4e5db6d64b67ad02511dfba1a1ef4ffddd9
3
+ size 5777
vocab.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "P": 4,
7
+ "N": 5,
8
+ "B": 6,
9
+ "R": 7,
10
+ "Q": 8,
11
+ "K": 9,
12
+ "a1": 10,
13
+ "a2": 11,
14
+ "a3": 12,
15
+ "a4": 13,
16
+ "a5": 14,
17
+ "a6": 15,
18
+ "a7": 16,
19
+ "a8": 17,
20
+ "b1": 18,
21
+ "b2": 19,
22
+ "b3": 20,
23
+ "b4": 21,
24
+ "b5": 22,
25
+ "b6": 23,
26
+ "b7": 24,
27
+ "b8": 25,
28
+ "c1": 26,
29
+ "c2": 27,
30
+ "c3": 28,
31
+ "c4": 29,
32
+ "c5": 30,
33
+ "c6": 31,
34
+ "c7": 32,
35
+ "c8": 33,
36
+ "d1": 34,
37
+ "d2": 35,
38
+ "d3": 36,
39
+ "d4": 37,
40
+ "d5": 38,
41
+ "d6": 39,
42
+ "d7": 40,
43
+ "d8": 41,
44
+ "e1": 42,
45
+ "e2": 43,
46
+ "e3": 44,
47
+ "e4": 45,
48
+ "e5": 46,
49
+ "e6": 47,
50
+ "e7": 48,
51
+ "e8": 49,
52
+ "f1": 50,
53
+ "f2": 51,
54
+ "f3": 52,
55
+ "f4": 53,
56
+ "f5": 54,
57
+ "f6": 55,
58
+ "f7": 56,
59
+ "f8": 57,
60
+ "g1": 58,
61
+ "g2": 59,
62
+ "g3": 60,
63
+ "g4": 61,
64
+ "g5": 62,
65
+ "g6": 63,
66
+ "g7": 64,
67
+ "g8": 65,
68
+ "h1": 66,
69
+ "h2": 67,
70
+ "h3": 68,
71
+ "h4": 69,
72
+ "h5": 70,
73
+ "h6": 71,
74
+ "h7": 72,
75
+ "h8": 73,
76
+ "(x)": 74,
77
+ "(+)": 75,
78
+ "(+*)": 76,
79
+ "(o)": 77,
80
+ "(O)": 78,
81
+ "=Q": 79,
82
+ "=R": 80,
83
+ "=B": 81,
84
+ "=N": 82
85
+ }