Sunxt25 commited on
Commit
519a223
·
verified ·
1 Parent(s): 218ccbc

Upload 4 files

Browse files
Files changed (4) hide show
  1. data.py +155 -0
  2. model.py +398 -0
  3. tokenizer.py +121 -0
  4. train.py +178 -0
data.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data loading utilities for the Chess Challenge using color+piece/from/to tokenizer.
3
+ """
4
+
5
+ from __future__ import annotations
6
+ from typing import Dict, Iterator, List, Optional
7
+ import torch
8
+ from torch.utils.data import Dataset
9
+
10
+ class ChessDataset(Dataset):
11
+ """
12
+ PyTorch Dataset for chess games with color+piece/from/to tokenizer.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ tokenizer,
18
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
19
+ split: str = "train",
20
+ column: str = "text",
21
+ max_length: int = 256,
22
+ max_samples: Optional[int] = None,
23
+ ):
24
+ from datasets import load_dataset
25
+
26
+ self.tokenizer = tokenizer
27
+ self.max_length = max_length
28
+ self.column = column
29
+
30
+ # Load dataset
31
+ dataset = load_dataset(dataset_name, split=split)
32
+ if max_samples is not None:
33
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
34
+ self.data = dataset
35
+
36
+ def __len__(self) -> int:
37
+ return len(self.data)
38
+
39
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
40
+ game = self.data[idx][self.column]
41
+
42
+ # Prepend BOS token
43
+ game_with_bos = self.tokenizer.bos_token + " " + game
44
+
45
+ # Tokenize: tokenizer 已经拆成 color+piece/from/to
46
+ encoding = self.tokenizer(
47
+ game_with_bos,
48
+ truncation=True,
49
+ max_length=self.max_length,
50
+ padding="max_length",
51
+ return_tensors="pt",
52
+ )
53
+
54
+ input_ids = encoding["input_ids"].squeeze(0)
55
+ attention_mask = encoding["attention_mask"].squeeze(0)
56
+
57
+ # Labels = input_ids (shift internally)
58
+ labels = input_ids.clone()
59
+ labels[attention_mask == 0] = -100 # ignore padding in loss
60
+
61
+ return {
62
+ "input_ids": input_ids,
63
+ "attention_mask": attention_mask,
64
+ "labels": labels,
65
+ }
66
+
67
+
68
+ class ChessDataCollator:
69
+ """Data collator for chess games."""
70
+
71
+ def __init__(self, tokenizer, max_length: int = 256):
72
+ self.tokenizer = tokenizer
73
+ self.max_length = max_length
74
+
75
+ def __call__(self, features: List[Dict]) -> Dict[str, torch.Tensor]:
76
+ input_ids = torch.stack([f["input_ids"] for f in features])
77
+ attention_mask = torch.stack([f["attention_mask"] for f in features])
78
+ labels = torch.stack([f["labels"] for f in features])
79
+ return {
80
+ "input_ids": input_ids,
81
+ "attention_mask": attention_mask,
82
+ "labels": labels,
83
+ }
84
+
85
+
86
+ def create_train_val_datasets(
87
+ tokenizer,
88
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
89
+ max_length: int = 256,
90
+ train_samples: Optional[int] = None,
91
+ val_samples: int = 5000,
92
+ val_ratio: float = 0.05,
93
+ ):
94
+ from datasets import load_dataset
95
+
96
+ full_dataset = load_dataset(dataset_name, split="train")
97
+ total = len(full_dataset)
98
+
99
+ if train_samples is not None:
100
+ n_train = min(train_samples, total - val_samples)
101
+ else:
102
+ n_train = int(total * (1 - val_ratio))
103
+
104
+ n_val = min(val_samples, total - n_train)
105
+
106
+ train_data = full_dataset.select(range(n_train))
107
+ val_data = full_dataset.select(range(n_train, n_train + n_val))
108
+
109
+ train_dataset = ChessDataset(tokenizer=tokenizer, dataset_name=dataset_name, max_length=max_length)
110
+ train_dataset.data = train_data
111
+
112
+ val_dataset = ChessDataset(tokenizer=tokenizer, dataset_name=dataset_name, max_length=max_length)
113
+ val_dataset.data = val_data
114
+
115
+ return train_dataset, val_dataset
116
+
117
+
118
+ def stream_games(dataset_name: str = "dlouapre/lichess_2025-01_1M", split: str = "train", column: str = "text") -> Iterator[str]:
119
+ """Stream games for memory-efficient processing."""
120
+ from datasets import load_dataset
121
+
122
+ dataset = load_dataset(dataset_name, split=split, streaming=True)
123
+ for example in dataset:
124
+ yield example[column]
125
+
126
+
127
+ def analyze_dataset_statistics(dataset_name: str = "dlouapre/lichess_2025-01_1M", max_samples: int = 10000) -> Dict:
128
+ """Analyze chess dataset statistics."""
129
+ from collections import Counter
130
+ from datasets import load_dataset
131
+
132
+ dataset = load_dataset(dataset_name, split="train")
133
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
134
+
135
+ game_lengths = []
136
+ move_counts = Counter()
137
+ opening_moves = Counter()
138
+
139
+ for example in dataset:
140
+ moves = example["text"].strip().split()
141
+ game_lengths.append(len(moves))
142
+ move_counts.update(moves)
143
+ if len(moves) >= 4:
144
+ opening = " ".join(moves[:4])
145
+ opening_moves[opening] += 1
146
+
147
+ return {
148
+ "total_games": len(dataset),
149
+ "avg_game_length": sum(game_lengths) / len(game_lengths),
150
+ "min_game_length": min(game_lengths),
151
+ "max_game_length": max(game_lengths),
152
+ "unique_moves": len(move_counts),
153
+ "most_common_moves": move_counts.most_common(20),
154
+ "most_common_openings": opening_moves.most_common(10),
155
+ }
model.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 144,
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=self.config.pad_token_id)
363
+ loss = loss_fct(
364
+ shift_logits.view(-1, shift_logits.size(-1)),
365
+ shift_labels.view(-1),
366
+ )
367
+
368
+ if not return_dict:
369
+ output = (logits,)
370
+ return ((loss,) + output) if loss is not None else output
371
+
372
+ return CausalLMOutputWithPast(
373
+ loss=loss,
374
+ logits=logits,
375
+ past_key_values=None,
376
+ hidden_states=None,
377
+ attentions=None,
378
+ )
379
+
380
+ @torch.no_grad()
381
+ def generate_move(self, input_ids, temperature=1.0, top_k=None, top_p=None):
382
+ self.eval()
383
+ next_tokens = []
384
+ for _ in range(3): # 生成 color+piece, from, to
385
+ outputs = self(input_ids)
386
+ logits = outputs.logits[:, -1, :] / temperature
387
+ # top-k / top-p 筛选
388
+ probs = F.softmax(logits, dim=-1)
389
+ next_token = torch.multinomial(probs, num_samples=1)
390
+ next_tokens.append(next_token)
391
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
392
+ return next_tokens # 返回三个 token id
393
+
394
+ # Register the model with Auto classes for easy loading
395
+ from transformers import AutoConfig, AutoModelForCausalLM
396
+
397
+ AutoConfig.register("chess_transformer", ChessConfig)
398
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
tokenizer.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ from typing import Dict, List, Optional
5
+ from transformers import PreTrainedTokenizer
6
+
7
+ class ChessTokenizer(PreTrainedTokenizer):
8
+ """
9
+ 符合评估脚本要求的 Chess Tokenizer。
10
+ 1. 词表大小为 144 (4 special + 12 pieces + 64 from_sq + 64 to_sq)。
11
+ 2. Decode 结果为紧凑格式(如 "WPe2e4"),确保 evaluate.py 的切片 [2:4] 和 [4:6] 正确。
12
+ 3. 区分起始格和目标格语义。
13
+ """
14
+
15
+ model_input_names = ["input_ids", "attention_mask"]
16
+ vocab_files_names = {"vocab_file": "vocab.json"}
17
+
18
+ PAD_TOKEN = "[PAD]"
19
+ BOS_TOKEN = "[BOS]"
20
+ EOS_TOKEN = "[EOS]"
21
+ UNK_TOKEN = "[UNK]"
22
+
23
+ def __init__(self, vocab_file: Optional[str] = None, vocab: Optional[Dict[str, int]] = None, **kwargs):
24
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
25
+
26
+ # 必须使用大写,以匹配 evaluate.py 生成的棋谱
27
+ self.colors_pieces = [f'{c}{p}' for c in ['W','B'] for p in ['P','N','B','R','Q','K']] # 12个
28
+ self.squares = [f'{f}{r}' for r in '12345678' for f in 'abcdefgh'] # 64个
29
+
30
+ if vocab is not None:
31
+ self._vocab = vocab
32
+ elif vocab_file is not None and os.path.exists(vocab_file):
33
+ with open(vocab_file, "r", encoding="utf-8") as f:
34
+ self._vocab = json.load(f)
35
+ else:
36
+ # 构建 144 大小的词表
37
+ self._vocab = {t: i for i, t in enumerate(special_tokens)} # 0-3
38
+
39
+ # 4-15: Piece tokens
40
+ for cp in self.colors_pieces:
41
+ self._vocab[cp] = len(self._vocab)
42
+
43
+ # 16-79: From Square tokens (内部带后缀防止重名)
44
+ for sq in self.squares:
45
+ self._vocab[f"{sq}_f"] = len(self._vocab)
46
+
47
+ # 80-143: To Square tokens
48
+ for sq in self.squares:
49
+ self._vocab[f"{sq}_t"] = len(self._vocab)
50
+
51
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
52
+
53
+ super().__init__(
54
+ pad_token=self.PAD_TOKEN,
55
+ bos_token=self.BOS_TOKEN,
56
+ eos_token=self.EOS_TOKEN,
57
+ unk_token=self.UNK_TOKEN,
58
+ **kwargs,
59
+ )
60
+
61
+ @property
62
+ def vocab_size(self) -> int:
63
+ return len(self._vocab)
64
+
65
+ def get_vocab(self) -> Dict[str, int]:
66
+ return dict(self._vocab)
67
+
68
+ def _tokenize(self, text: str) -> List[str]:
69
+ """将 WPe2e4 拆分为三个 token"""
70
+ tokens = []
71
+ # 处理可能的空格分隔(如历史棋谱)
72
+ moves = text.strip().split()
73
+ for move in moves:
74
+ # 过滤特殊 token 字符串
75
+ if move in [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]:
76
+ tokens.append(move)
77
+ continue
78
+
79
+ if len(move) >= 6:
80
+ cp = move[:2] # 例如 "WP"
81
+ from_sq = move[2:4] + "_f" # 例如 "e2_f"
82
+ to_sq = move[4:6] + "_t" # 例如 "e4_t"
83
+ tokens.extend([cp, from_sq, to_sq])
84
+ return tokens
85
+
86
+ def _convert_token_to_id(self, token: str) -> int:
87
+ return self._vocab.get(token, self._vocab[self.UNK_TOKEN])
88
+
89
+ def _convert_id_to_token(self, index: int) -> str:
90
+ token = self._ids_to_tokens.get(index, self.UNK_TOKEN)
91
+ # 关键:在 decode 时去掉内部后缀,还原为 "e2", "e4"
92
+ return token.replace("_f", "").replace("_t", "")
93
+
94
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
95
+ """
96
+ 将 token 列表合并。
97
+ evaluate.py 要求输出如 "WPe2e4",因此这里不加空格。
98
+ """
99
+ # 过滤特殊 token,只保留棋步内容
100
+ clean_tokens = [t for t in tokens if t not in self.all_special_tokens]
101
+ return "".join(clean_tokens)
102
+
103
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple:
104
+ if not os.path.isdir(save_directory):
105
+ os.makedirs(save_directory, exist_ok=True)
106
+ vocab_file = os.path.join(
107
+ save_directory,
108
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json"
109
+ )
110
+ with open(vocab_file, "w", encoding="utf-8") as f:
111
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
112
+ return (vocab_file,)
113
+
114
+ @classmethod
115
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs) -> "ChessTokenizer":
116
+ vocab_file = os.path.join(pretrained_model_name_or_path, "vocab.json")
117
+ if not os.path.exists(vocab_file):
118
+ return cls() # 如果没有文件则初始化默认的
119
+ with open(vocab_file, "r", encoding="utf-8") as f:
120
+ vocab = json.load(f)
121
+ return cls(vocab=vocab, **kwargs)
train.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training script for the Chess Challenge.
3
+
4
+ This script provides a complete training pipeline using the Hugging Face Trainer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import signal
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ import torch
16
+ from transformers import (
17
+ Trainer,
18
+ TrainingArguments,
19
+ set_seed,
20
+ )
21
+
22
+ from src.data import ChessDataCollator, create_train_val_datasets
23
+ from src.model import ChessConfig, ChessForCausalLM
24
+ from src.tokenizer import ChessTokenizer
25
+ from src.utils import count_parameters, print_parameter_budget
26
+
27
+
28
+ def parse_args():
29
+ """Parse command line arguments."""
30
+ parser = argparse.ArgumentParser(
31
+ description="Train a chess-playing language model"
32
+ )
33
+
34
+ # Model arguments
35
+ parser.add_argument("--n_embd", type=int, default=128, help="Embedding dimension")
36
+ parser.add_argument("--n_layer", type=int, default=5, help="Number of transformer layers")
37
+ parser.add_argument("--n_head", type=int, default=4, help="Number of attention heads")
38
+ parser.add_argument("--n_ctx", type=int, default=256, help="Maximum context length")
39
+ parser.add_argument("--n_inner", type=int, default=None, help="Feed-forward inner dimension")
40
+ parser.add_argument("--no_tie_weights", action="store_true", help="Disable weight tying")
41
+
42
+ # Data arguments
43
+ parser.add_argument("--dataset_name", type=str, default="dlouapre/lichess_2025-01_1M", help="Hugging Face dataset name")
44
+ parser.add_argument("--max_train_samples", type=int, default=None, help="Maximum number of training samples")
45
+ parser.add_argument("--val_samples", type=int, default=5000, help="Number of validation samples")
46
+
47
+ # Training arguments
48
+ parser.add_argument("--output_dir", type=str, default="./my_model", help="Output directory")
49
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Number of epochs")
50
+ parser.add_argument("--per_device_train_batch_size", type=int, default=32, help="Training batch size")
51
+ parser.add_argument("--per_device_eval_batch_size", type=int, default=64, help="Evaluation batch size")
52
+ parser.add_argument("--learning_rate", type=float, default=5e-4, help="Learning rate")
53
+ parser.add_argument("--weight_decay", type=float, default=0.01, help="Weight decay")
54
+ parser.add_argument("--warmup_ratio", type=float, default=0.1, help="Warmup ratio")
55
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
56
+
57
+ # Logging arguments
58
+ parser.add_argument("--logging_steps", type=int, default=100, help="Logging frequency")
59
+ parser.add_argument("--eval_steps", type=int, default=500, help="Evaluation frequency")
60
+ parser.add_argument("--save_steps", type=int, default=1000, help="Checkpoint saving frequency")
61
+
62
+ return parser.parse_args()
63
+
64
+
65
+ def main():
66
+ """Main training function."""
67
+ args = parse_args()
68
+ set_seed(args.seed)
69
+
70
+ print("=" * 60)
71
+ print("CHESS CHALLENGE - TRAINING")
72
+ print("=" * 60)
73
+
74
+ # --- Build tokenizer ---
75
+ print("\nBuilding tokenizer from dataset...")
76
+ tokenizer = ChessTokenizer()
77
+ print(f" Vocabulary size: {tokenizer.vocab_size}")
78
+
79
+ # --- Model configuration ---
80
+ print("\nCreating model configuration...")
81
+ config = ChessConfig(
82
+ vocab_size=tokenizer.vocab_size, # 使用 tokenizer 实际 vocab_size
83
+ n_embd=args.n_embd,
84
+ n_layer=args.n_layer,
85
+ n_head=args.n_head,
86
+ n_ctx=args.n_ctx,
87
+ n_inner=args.n_inner,
88
+ dropout=0.1,
89
+ tie_weights=not args.no_tie_weights,
90
+ pad_token_id=tokenizer.pad_token_id,
91
+ bos_token_id=tokenizer.bos_token_id,
92
+ eos_token_id=tokenizer.eos_token_id,
93
+ )
94
+
95
+ # 打印参数预算
96
+ print_parameter_budget(config)
97
+
98
+ # --- Create model ---
99
+ print("\nCreating model...")
100
+ model = ChessForCausalLM(config)
101
+ model = ChessForCausalLM.from_pretrained("./my_model/checkpoints")
102
+ n_params = count_parameters(model)
103
+ print(f" Total parameters: {n_params:,}")
104
+ if n_params > 1_000_000:
105
+ print("WARNING: Model exceeds 1M parameter limit!")
106
+ else:
107
+ print("✓ Model is within 1M parameter limit")
108
+
109
+ # --- Load datasets ---
110
+ print("\nLoading datasets...")
111
+ train_dataset, val_dataset = create_train_val_datasets(
112
+ tokenizer=tokenizer,
113
+ dataset_name=args.dataset_name,
114
+ max_length=args.n_ctx,
115
+ train_samples=args.max_train_samples,
116
+ val_samples=args.val_samples,
117
+ )
118
+ print(f" Training samples: {len(train_dataset):,}")
119
+ print(f" Validation samples: {len(val_dataset):,}")
120
+
121
+ # --- Data collator ---
122
+ data_collator = ChessDataCollator(tokenizer, max_length=args.n_ctx)
123
+
124
+ # --- Training arguments ---
125
+ training_args = TrainingArguments(
126
+ output_dir=args.output_dir,
127
+ num_train_epochs=args.num_train_epochs,
128
+ per_device_train_batch_size=args.per_device_train_batch_size,
129
+ per_device_eval_batch_size=args.per_device_eval_batch_size,
130
+ learning_rate=args.learning_rate,
131
+ weight_decay=args.weight_decay,
132
+ warmup_ratio=args.warmup_ratio,
133
+ logging_dir=os.path.join(args.output_dir, "logs"),
134
+ logging_steps=args.logging_steps,
135
+ eval_strategy="epoch",
136
+ save_strategy="epoch",
137
+ save_total_limit=3,
138
+ load_best_model_at_end=True,
139
+ metric_for_best_model="eval_loss",
140
+ greater_is_better=False,
141
+ seed=args.seed,
142
+ bf16=torch.cuda.is_available() and torch.cuda.is_bf16_supported(),
143
+ report_to=["none"],
144
+ )
145
+
146
+ # --- Trainer ---
147
+ trainer = Trainer(
148
+ model=model,
149
+ args=training_args,
150
+ train_dataset=train_dataset,
151
+ eval_dataset=val_dataset,
152
+ data_collator=data_collator,
153
+ tokenizer=tokenizer,
154
+ )
155
+
156
+ # --- Ctrl+C checkpoint handler ---
157
+ def save_checkpoint(sig, frame):
158
+ print("\n⚠️ KeyboardInterrupt detected. Saving checkpoint...")
159
+ trainer.save_model(os.path.join(args.output_dir, "checkpoints"))
160
+ tokenizer.save_pretrained(os.path.join(args.output_dir, "checkpoints"))
161
+ sys.exit(0)
162
+
163
+ signal.signal(signal.SIGINT, save_checkpoint)
164
+
165
+ # --- Train ---
166
+ print("\nStarting training...")
167
+ trainer.train()
168
+
169
+ # --- Save final model ---
170
+ print("\nSaving final model...")
171
+ trainer.save_model(os.path.join(args.output_dir, "final_model"))
172
+ tokenizer.save_pretrained(os.path.join(args.output_dir, "final_model"))
173
+ print("\nTraining complete!")
174
+ print(f" Model saved to: {args.output_dir}/my_model")
175
+
176
+
177
+ if __name__ == "__main__":
178
+ main()