OussamaleZ commited on
Commit
11a86e5
·
verified ·
1 Parent(s): 784d469

Chess Challenge submission by OussamaleZ

Browse files
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_oussamalez_overfit
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [OussamaleZ](https://huggingface.co/OussamaleZ)
17
+ - **Parameters**: 931,840
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_oussamalez_overfit", trust_remote_code=True)
26
+ tokenizer = AutoTokenizer.from_pretrained("LLM-course/chess_oussamalez_overfit", 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,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "dropout": 0.2,
7
+ "dtype": "float32",
8
+ "eos_token_id": 2,
9
+ "layer_norm_epsilon": 1e-05,
10
+ "model_type": "chess_transformer",
11
+ "n_ctx": 350,
12
+ "n_embd": 160,
13
+ "n_head": 4,
14
+ "n_inner": 160,
15
+ "n_kv_head": 4,
16
+ "n_layer": 5,
17
+ "pad_token_id": 0,
18
+ "tie_weights": false,
19
+ "tie_word_embeddings": false,
20
+ "transformers_version": "4.57.6",
21
+ "vocab_size": 81,
22
+ "auto_map": {
23
+ "AutoConfig": "model.ChessConfig",
24
+ "AutoModelForCausalLM": "model.ChessForCausalLM"
25
+ }
26
+ }
model.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_kv_head: Optional[int] = None,
60
+ n_ctx: int = 256,
61
+ n_inner: Optional[int] = None,
62
+ dropout: float = 0.1,
63
+ layer_norm_epsilon: float = 1e-5,
64
+ tie_weights: bool = True,
65
+ pad_token_id: int = 0,
66
+ bos_token_id: int = 1,
67
+ eos_token_id: int = 2,
68
+ **kwargs,
69
+ ):
70
+ super().__init__(
71
+ pad_token_id=pad_token_id,
72
+ bos_token_id=bos_token_id,
73
+ eos_token_id=eos_token_id,
74
+ **kwargs,
75
+ )
76
+
77
+ self.vocab_size = vocab_size
78
+ self.n_embd = n_embd
79
+ self.n_layer = n_layer
80
+ self.n_head = n_head
81
+ self.n_kv_head = n_kv_head if n_kv_head is not None else n_head
82
+ self.n_ctx = n_ctx
83
+ self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
84
+ self.dropout = dropout
85
+ self.layer_norm_epsilon = layer_norm_epsilon
86
+ self.tie_weights = tie_weights
87
+ # Inform HF base class about tying behavior
88
+ self.tie_word_embeddings = bool(tie_weights)
89
+
90
+
91
+ class MultiHeadAttention(nn.Module):
92
+ """
93
+ Multi-head self-attention module.
94
+
95
+ This is a standard scaled dot-product attention implementation
96
+ with causal masking for autoregressive generation.
97
+ """
98
+
99
+ def __init__(self, config: ChessConfig):
100
+ super().__init__()
101
+
102
+ assert config.n_embd % config.n_head == 0, \
103
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
104
+ assert config.n_head % config.n_kv_head == 0, \
105
+ f"n_head ({config.n_head}) must be divisible by n_kv_head ({config.n_kv_head})"
106
+
107
+ self.n_head = config.n_head
108
+ self.n_kv_head = config.n_kv_head
109
+ self.n_embd = config.n_embd
110
+ self.head_dim = config.n_embd // config.n_head
111
+ assert self.head_dim % 2 == 0, "RoPE requires an even head_dim"
112
+ self.kv_repeat = self.n_head // self.n_kv_head
113
+
114
+ # Q and KV projections (GQA)
115
+ self.q_proj = nn.Linear(config.n_embd, self.n_head * self.head_dim)
116
+ self.kv_proj = nn.Linear(config.n_embd, 2 * self.n_kv_head * self.head_dim)
117
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
118
+
119
+ self.dropout = nn.Dropout(config.dropout)
120
+ self.q_norm = nn.LayerNorm(self.head_dim)
121
+ self.k_norm = nn.LayerNorm(self.head_dim)
122
+
123
+ # Causal mask (will be created on first forward pass)
124
+ self.register_buffer(
125
+ "bias",
126
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
127
+ 1, 1, config.n_ctx, config.n_ctx
128
+ ),
129
+ persistent=False,
130
+ )
131
+ self.register_buffer(
132
+ "rope_cache",
133
+ self._build_rope_cache(config.n_ctx, self.head_dim),
134
+ persistent=False,
135
+ )
136
+
137
+ def _build_rope_cache(self, n_ctx: int, head_dim: int) -> torch.Tensor:
138
+ """Precompute cos/sin for RoPE."""
139
+ position = torch.arange(n_ctx, dtype=torch.float)
140
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, head_dim, 2, dtype=torch.float) / head_dim))
141
+ freqs = torch.einsum("i,j->ij", position, inv_freq)
142
+ cos = torch.cos(freqs)
143
+ sin = torch.sin(freqs)
144
+ return torch.stack((cos, sin), dim=0)
145
+
146
+ def _apply_rope(self, x: torch.Tensor, seq_len: int) -> torch.Tensor:
147
+ """Apply rotary positional embedding to q/k."""
148
+ # x: (batch, head, seq, head_dim)
149
+ cos = self.rope_cache[0, :seq_len, :].to(x.device)
150
+ sin = self.rope_cache[1, :seq_len, :].to(x.device)
151
+ cos = cos.unsqueeze(0).unsqueeze(0)
152
+ sin = sin.unsqueeze(0).unsqueeze(0)
153
+ x1 = x[..., 0::2]
154
+ x2 = x[..., 1::2]
155
+ x_rot = torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
156
+ return x_rot
157
+
158
+ def forward(
159
+ self,
160
+ x: torch.Tensor,
161
+ attention_mask: Optional[torch.Tensor] = None,
162
+ ) -> torch.Tensor:
163
+ batch_size, seq_len, _ = x.size()
164
+
165
+ # Compute Q, K, V (GQA)
166
+ q = self.q_proj(x)
167
+ kv = self.kv_proj(x)
168
+ k, v = kv.split(self.n_kv_head * self.head_dim, dim=2)
169
+
170
+ # Reshape for multi-head attention
171
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
172
+ k = k.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
173
+ v = v.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
174
+
175
+ # QK-Norm
176
+ q = self.q_norm(q)
177
+ k = self.k_norm(k)
178
+
179
+ # Repeat KV heads to match Q heads
180
+ if self.kv_repeat > 1:
181
+ k = k.repeat_interleave(self.kv_repeat, dim=1)
182
+ v = v.repeat_interleave(self.kv_repeat, dim=1)
183
+
184
+ # Apply RoPE to queries and keys
185
+ q = self._apply_rope(q, seq_len)
186
+ k = self._apply_rope(k, seq_len)
187
+
188
+ # Scaled dot-product attention
189
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
190
+
191
+ # Apply causal mask
192
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
193
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
194
+
195
+ # Apply attention mask (for padding)
196
+ if attention_mask is not None:
197
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
198
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
199
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
200
+
201
+ attn_weights = F.softmax(attn_weights, dim=-1)
202
+ attn_weights = self.dropout(attn_weights)
203
+
204
+ # Apply attention to values
205
+ attn_output = torch.matmul(attn_weights, v)
206
+
207
+ # Reshape back
208
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
209
+ batch_size, seq_len, self.n_embd
210
+ )
211
+
212
+ # Output projection
213
+ attn_output = self.c_proj(attn_output)
214
+
215
+ return attn_output
216
+
217
+
218
+ class FeedForward(nn.Module):
219
+ """
220
+ Feed-forward network (MLP) module.
221
+
222
+ SwiGLU-style MLP for better quality at small scale.
223
+ """
224
+
225
+ def __init__(self, config: ChessConfig):
226
+ super().__init__()
227
+
228
+ self.c_fc = nn.Linear(config.n_embd, 2 * config.n_inner)
229
+ self.c_proj = nn.Linear(config.n_inner, config.n_embd)
230
+ self.dropout = nn.Dropout(config.dropout)
231
+
232
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
233
+ x = self.c_fc(x)
234
+ x, gate = x.chunk(2, dim=-1)
235
+ x = F.silu(x) * gate
236
+ x = self.c_proj(x)
237
+ x = self.dropout(x)
238
+ return x
239
+
240
+
241
+ class TransformerBlock(nn.Module):
242
+ """
243
+ A single transformer block with attention and feed-forward layers.
244
+
245
+ Uses pre-normalization (LayerNorm before attention/FFN) for better
246
+ training stability.
247
+ """
248
+
249
+ def __init__(self, config: ChessConfig):
250
+ super().__init__()
251
+
252
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
253
+ self.attn = MultiHeadAttention(config)
254
+ self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
255
+ self.mlp = FeedForward(config)
256
+
257
+ def forward(
258
+ self,
259
+ x: torch.Tensor,
260
+ attention_mask: Optional[torch.Tensor] = None,
261
+ ) -> torch.Tensor:
262
+ # Pre-norm attention
263
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
264
+ # Pre-norm FFN
265
+ x = x + self.mlp(self.ln_2(x))
266
+ return x
267
+
268
+
269
+ class ChessForCausalLM(PreTrainedModel):
270
+ """
271
+ Chess Transformer for Causal Language Modeling (next-move prediction).
272
+
273
+ This model is designed to predict the next chess move given a sequence
274
+ of previous moves. It uses a GPT-style architecture with:
275
+ - Token embeddings for chess moves
276
+ - Learned positional embeddings
277
+ - Stacked transformer blocks
278
+ - Linear head for next-token prediction
279
+
280
+ The model supports weight tying between the embedding layer and the
281
+ output projection to save parameters.
282
+
283
+ Example:
284
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
285
+ >>> model = ChessForCausalLM(config)
286
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
287
+ >>> outputs = model(**inputs)
288
+ >>> next_move_logits = outputs.logits[:, -1, :]
289
+ """
290
+
291
+ config_class = ChessConfig
292
+ base_model_prefix = "transformer"
293
+ supports_gradient_checkpointing = True
294
+ # Suppress missing-key warning for tied lm_head when loading
295
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
296
+
297
+ def __init__(self, config: ChessConfig):
298
+ super().__init__(config)
299
+
300
+ # Token embeddings (RoPE is applied inside attention)
301
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
302
+
303
+ self.drop = nn.Dropout(config.dropout)
304
+
305
+ # Transformer blocks
306
+ self.h = nn.ModuleList([
307
+ TransformerBlock(config) for _ in range(config.n_layer)
308
+ ])
309
+
310
+ # Final layer norm
311
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
312
+
313
+ # Output head
314
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
315
+
316
+ # Declare tied weights for proper serialization
317
+ if config.tie_weights:
318
+ self._tied_weights_keys = ["lm_head.weight"]
319
+
320
+ # Initialize weights
321
+ self.post_init()
322
+
323
+ # Tie weights if configured
324
+ if config.tie_weights:
325
+ self.tie_weights()
326
+
327
+
328
+ def get_input_embeddings(self) -> nn.Module:
329
+ return self.wte
330
+
331
+ def set_input_embeddings(self, new_embeddings: nn.Module):
332
+ self.wte = new_embeddings
333
+ if getattr(self.config, "tie_weights", False):
334
+ self.tie_weights()
335
+
336
+ def get_output_embeddings(self) -> nn.Module:
337
+ return self.lm_head
338
+
339
+ def set_output_embeddings(self, new_embeddings: nn.Module):
340
+ self.lm_head = new_embeddings
341
+
342
+ def tie_weights(self):
343
+ # Use HF helper to tie or clone depending on config
344
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
345
+ self._tie_or_clone_weights(self.lm_head, self.wte)
346
+
347
+ def _init_weights(self, module: nn.Module):
348
+ """Initialize weights following GPT-2 style."""
349
+ if isinstance(module, nn.Linear):
350
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
351
+ if module.bias is not None:
352
+ torch.nn.init.zeros_(module.bias)
353
+ elif isinstance(module, nn.Embedding):
354
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
355
+ elif isinstance(module, nn.LayerNorm):
356
+ torch.nn.init.ones_(module.weight)
357
+ torch.nn.init.zeros_(module.bias)
358
+
359
+ def forward(
360
+ self,
361
+ input_ids: torch.LongTensor,
362
+ attention_mask: Optional[torch.Tensor] = None,
363
+ position_ids: Optional[torch.LongTensor] = None,
364
+ labels: Optional[torch.LongTensor] = None,
365
+ return_dict: Optional[bool] = None,
366
+ **kwargs,
367
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
368
+ """
369
+ Forward pass of the model.
370
+
371
+ Args:
372
+ input_ids: Token IDs of shape (batch_size, seq_len).
373
+ attention_mask: Attention mask of shape (batch_size, seq_len).
374
+ position_ids: Position IDs of shape (batch_size, seq_len).
375
+ labels: Labels for language modeling loss.
376
+ return_dict: Whether to return a ModelOutput object.
377
+
378
+ Returns:
379
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
380
+ """
381
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
382
+
383
+ batch_size, seq_len = input_ids.size()
384
+ device = input_ids.device
385
+
386
+ # Get embeddings
387
+ token_embeds = self.wte(input_ids)
388
+ hidden_states = self.drop(token_embeds)
389
+
390
+ # Pass through transformer blocks
391
+ for block in self.h:
392
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
393
+
394
+ # Final layer norm
395
+ hidden_states = self.ln_f(hidden_states)
396
+
397
+ # Get logits
398
+ logits = self.lm_head(hidden_states)
399
+
400
+ # Compute loss if labels are provided
401
+ loss = None
402
+ if labels is not None:
403
+ # Shift logits and labels for next-token prediction
404
+ shift_logits = logits[..., :-1, :].contiguous()
405
+ shift_labels = labels[..., 1:].contiguous()
406
+
407
+ # Flatten for cross-entropy
408
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
409
+ # loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
410
+ loss = loss_fct(
411
+ shift_logits.view(-1, shift_logits.size(-1)),
412
+ shift_labels.view(-1),
413
+ )
414
+
415
+ if not return_dict:
416
+ output = (logits,)
417
+ return ((loss,) + output) if loss is not None else output
418
+
419
+ return CausalLMOutputWithPast(
420
+ loss=loss,
421
+ logits=logits,
422
+ past_key_values=None,
423
+ hidden_states=None,
424
+ attentions=None,
425
+ )
426
+
427
+ @torch.no_grad()
428
+ def generate_move(
429
+ self,
430
+ input_ids: torch.LongTensor,
431
+ temperature: float = 1.0,
432
+ top_k: Optional[int] = None,
433
+ top_p: Optional[float] = None,
434
+ ) -> int:
435
+ """
436
+ Generate the next move given a sequence of moves.
437
+
438
+ Args:
439
+ input_ids: Token IDs of shape (1, seq_len).
440
+ temperature: Sampling temperature (1.0 = no change).
441
+ top_k: If set, only sample from top k tokens.
442
+ top_p: If set, use nucleus sampling with this threshold.
443
+
444
+ Returns:
445
+ The token ID of the predicted next move.
446
+ """
447
+ self.eval()
448
+
449
+ # Get logits for the last position
450
+ outputs = self(input_ids)
451
+ logits = outputs.logits[:, -1, :] / temperature
452
+
453
+ # Apply top-k filtering
454
+ if top_k is not None:
455
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
456
+ logits[indices_to_remove] = float("-inf")
457
+
458
+ # Apply top-p (nucleus) filtering
459
+ if top_p is not None:
460
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
461
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
462
+
463
+ # Remove tokens with cumulative probability above the threshold
464
+ sorted_indices_to_remove = cumulative_probs > top_p
465
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
466
+ sorted_indices_to_remove[..., 0] = 0
467
+
468
+ indices_to_remove = sorted_indices_to_remove.scatter(
469
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
470
+ )
471
+ logits[indices_to_remove] = float("-inf")
472
+
473
+ # Sample from the distribution
474
+ probs = F.softmax(logits, dim=-1)
475
+ next_token = torch.multinomial(probs, num_samples=1)
476
+
477
+ return next_token.item()
478
+
479
+
480
+ # Register the model with Auto classes for easy loading
481
+ from transformers import AutoConfig, AutoModelForCausalLM
482
+
483
+ AutoConfig.register("chess_transformer", ChessConfig)
484
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25c5b4b84e1f87b085ffd943659c7b189ac9327d4f5681e89b417dd380b548c2
3
+ size 3735400
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63fac4b0e8a1d61e1e22525ffd554389e8dcf49e9f6af8f7dc8a76245c8f962d
3
+ size 7533515
rng_state.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9459ef058cdba57aad3012a1900a3d266dc4f4e9a4251f413a14d42617a25f03
3
+ size 14645
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fd0a3aac54aaa944a0044de0e74c345d60a2a4f26f4623035f59b54caf1ee3f
3
+ size 1465
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,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom Chess Tokenizer for the Chess Challenge.
3
+
4
+ This tokenizer treats each move as a single token using the extended UCI notation
5
+ from the Lichess dataset (e.g., WPe2e4, BNg8f6).
6
+
7
+ The dataset format uses:
8
+ - W/B prefix for White/Black
9
+ - Piece letter: P=Pawn, N=Knight, B=Bishop, R=Rook, Q=Queen, K=King
10
+ - Source and destination squares (e.g., e2e4)
11
+ - Special suffixes: (x)=capture, (+)=check, (+*)=checkmate, (o)/(O)=castling
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ from typing import Dict, List, Optional
20
+
21
+ from transformers import PreTrainedTokenizer
22
+
23
+
24
+ class ChessTokenizer(PreTrainedTokenizer):
25
+ """
26
+ A custom tokenizer for chess moves using extended UCI notation.
27
+
28
+ This tokenizer maps each possible chess move to a unique token ID.
29
+ The vocabulary is built from the training dataset to ensure all moves
30
+ encountered during training have a corresponding token.
31
+
32
+ Example:
33
+ >>> tokenizer = ChessTokenizer()
34
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
35
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
36
+ """
37
+
38
+ model_input_names = ["input_ids", "attention_mask"]
39
+ vocab_files_names = {"vocab_file": "vocab.json"}
40
+
41
+ # Special tokens
42
+ PAD_TOKEN = "[PAD]"
43
+ BOS_TOKEN = "[BOS]"
44
+ EOS_TOKEN = "[EOS]"
45
+ UNK_TOKEN = "[UNK]"
46
+
47
+ def __init__(
48
+ self,
49
+ vocab_file: Optional[str] = None,
50
+ vocab: Optional[Dict[str, int]] = None,
51
+ **kwargs,
52
+ ):
53
+ """
54
+ Initialize the chess tokenizer.
55
+
56
+ Args:
57
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
58
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
59
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
60
+ """
61
+ # Initialize special tokens
62
+ self._pad_token = self.PAD_TOKEN
63
+ self._bos_token = self.BOS_TOKEN
64
+ self._eos_token = self.EOS_TOKEN
65
+ self._unk_token = self.UNK_TOKEN
66
+
67
+ # Remove any duplicate special-token entries passed through kwargs
68
+ # to avoid "multiple values for keyword" errors when loading from disk.
69
+ kwargs.pop("pad_token", None)
70
+ kwargs.pop("bos_token", None)
71
+ kwargs.pop("eos_token", None)
72
+ kwargs.pop("unk_token", None)
73
+
74
+ # Load or create vocabulary
75
+ if vocab is not None:
76
+ self._vocab = vocab
77
+ elif vocab_file is not None and os.path.exists(vocab_file):
78
+ with open(vocab_file, "r", encoding="utf-8") as f:
79
+ self._vocab = json.load(f)
80
+ else:
81
+ # Create a minimal vocabulary with just special tokens
82
+ # The full vocabulary should be built from the dataset
83
+ self._vocab = self._create_default_vocab()
84
+
85
+ # Create reverse mapping
86
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
87
+
88
+ # Call parent init AFTER setting up vocab
89
+ super().__init__(
90
+ pad_token=self._pad_token,
91
+ bos_token=self._bos_token,
92
+ eos_token=self._eos_token,
93
+ unk_token=self._unk_token,
94
+ **kwargs,
95
+ )
96
+
97
+ def _create_default_vocab(self) -> Dict[str, int]:
98
+ """
99
+ Create a minimal default vocabulary with just special tokens.
100
+
101
+ For the full vocabulary, use `build_vocab_from_dataset()`.
102
+ This minimal vocab is just a placeholder - you should build from data.
103
+ """
104
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
105
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
106
+ return vocab
107
+
108
+ @staticmethod
109
+ def split_move(move: str) -> List[str]:
110
+ tokens = [move[0:2], move[2:4], move[4:6]]
111
+ if "=" in move:
112
+ promo = move.split("=", 1)[1][:1]
113
+ if promo:
114
+ tokens.append(promo.upper())
115
+ tokens.append(' ')
116
+ return tokens
117
+
118
+ @classmethod
119
+ def build_vocab_from_iterator(
120
+ cls,
121
+ iterator,
122
+ min_frequency: int = 1,
123
+ ) -> "ChessTokenizer":
124
+ """
125
+ Build a tokenizer vocabulary from an iterator of game strings.
126
+
127
+ Args:
128
+ iterator: An iterator yielding game strings (space-separated moves).
129
+ min_frequency: Minimum frequency for a token to be included.
130
+
131
+ Returns:
132
+ A ChessTokenizer with the built vocabulary.
133
+ """
134
+ from collections import Counter
135
+
136
+ token_counts = Counter()
137
+
138
+ for game in iterator:
139
+ moves = game.strip().split()
140
+ for move in moves:
141
+ token_counts.update(cls.split_move(move))
142
+
143
+ # Filter by frequency
144
+ tokens = [
145
+ token for token, count in token_counts.items()
146
+ if count >= min_frequency
147
+ ]
148
+
149
+ # Sort for reproducibility
150
+ tokens = sorted(tokens)
151
+
152
+ # Build vocabulary
153
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
154
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
155
+
156
+ return cls(vocab=vocab)
157
+
158
+ @classmethod
159
+ def build_vocab_from_dataset(
160
+ cls,
161
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
162
+ split: str = "train",
163
+ column: str = "text",
164
+ min_frequency: int = 500,
165
+ max_samples: Optional[int] = 100000,
166
+ ) -> "ChessTokenizer":
167
+ """
168
+ Build a tokenizer vocabulary from a Hugging Face dataset.
169
+
170
+ Args:
171
+ dataset_name: Name of the dataset on Hugging Face Hub.
172
+ split: Dataset split to use.
173
+ column: Column containing the game strings.
174
+ min_frequency: Minimum frequency for a token to be included (default: 500).
175
+ max_samples: Maximum number of samples to process (default: 100k).
176
+
177
+ Returns:
178
+ A ChessTokenizer with the built vocabulary.
179
+ """
180
+ from datasets import load_dataset
181
+
182
+ dataset = load_dataset(dataset_name, split=split)
183
+
184
+ if max_samples is not None:
185
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
186
+
187
+ def game_iterator():
188
+ for example in dataset:
189
+ yield example[column]
190
+
191
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
192
+
193
+ @property
194
+ def vocab_size(self) -> int:
195
+ """Return the size of the vocabulary."""
196
+ return len(self._vocab)
197
+
198
+ def get_vocab(self) -> Dict[str, int]:
199
+ """Return the vocabulary as a dictionary."""
200
+ return dict(self._vocab)
201
+
202
+ def _tokenize(self, text: str) -> List[str]:
203
+ """
204
+ Tokenize a string of moves into a list of tokens.
205
+
206
+ Args:
207
+ text: A string of space-separated moves.
208
+
209
+ Returns:
210
+ List of move tokens.
211
+ """
212
+ moves = text.strip().split()
213
+ out = []
214
+ for move in moves:
215
+ out += self.split_move(move)
216
+ return out
217
+
218
+ def _convert_token_to_id(self, token: str) -> int:
219
+ """Convert a token to its ID."""
220
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
221
+
222
+ def _convert_id_to_token(self, index: int) -> str:
223
+ """Convert an ID to its token."""
224
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
225
+
226
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
227
+ """Convert a list of tokens back to a string."""
228
+ # Filter out special tokens for cleaner output
229
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
230
+ return " ".join(t for t in tokens if t not in special)
231
+
232
+ def save_vocabulary(
233
+ self,
234
+ save_directory: str,
235
+ filename_prefix: Optional[str] = None,
236
+ ) -> tuple:
237
+ """
238
+ Save the vocabulary to a JSON file.
239
+
240
+ Args:
241
+ save_directory: Directory to save the vocabulary.
242
+ filename_prefix: Optional prefix for the filename.
243
+
244
+ Returns:
245
+ Tuple containing the path to the saved vocabulary file.
246
+ """
247
+ if not os.path.isdir(save_directory):
248
+ os.makedirs(save_directory, exist_ok=True)
249
+
250
+ vocab_file = os.path.join(
251
+ save_directory,
252
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
253
+ )
254
+
255
+ with open(vocab_file, "w", encoding="utf-8") as f:
256
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
257
+
258
+ return (vocab_file,)
259
+
260
+
261
+ def count_vocab_from_dataset(
262
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
263
+ split: str = "train",
264
+ column: str = "text",
265
+ max_samples: Optional[int] = 10000,
266
+ ) -> Dict[str, int]:
267
+ """
268
+ Count token frequencies in a dataset (useful for vocabulary analysis).
269
+
270
+ Args:
271
+ dataset_name: Name of the dataset on Hugging Face Hub.
272
+ split: Dataset split to use.
273
+ column: Column containing the game strings.
274
+ max_samples: Maximum number of samples to process.
275
+
276
+ Returns:
277
+ Dictionary mapping tokens to their frequencies.
278
+ """
279
+ from collections import Counter
280
+ from datasets import load_dataset
281
+
282
+ dataset = load_dataset(dataset_name, split=split)
283
+
284
+ if max_samples is not None:
285
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
286
+
287
+ token_counts = Counter()
288
+
289
+ for example in dataset:
290
+ moves = example[column].strip().split()
291
+ token_counts.update(moves)
292
+
293
+ return dict(token_counts)
tokenizer_config.json ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[BOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[EOS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[UNK]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ }
35
+ },
36
+ "bos_token": "[BOS]",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "[EOS]",
39
+ "extra_special_tokens": {},
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": "[PAD]",
42
+ "tokenizer_class": "ChessTokenizer",
43
+ "unk_token": "[UNK]",
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenizer.ChessTokenizer",
47
+ null
48
+ ]
49
+ }
50
+ }
trainer_state.json ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": 4000,
3
+ "best_metric": 0.7102092504501343,
4
+ "best_model_checkpoint": "/Data/data_chess/checkpoint-4000",
5
+ "epoch": 0.2694691457828079,
6
+ "eval_steps": 500,
7
+ "global_step": 4000,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0.006736728644570197,
14
+ "grad_norm": 0.7572135925292969,
15
+ "learning_rate": 0.0006644295302013424,
16
+ "loss": 2.9711,
17
+ "step": 100
18
+ },
19
+ {
20
+ "epoch": 0.013473457289140393,
21
+ "grad_norm": 0.6671218276023865,
22
+ "learning_rate": 0.0009999714348540981,
23
+ "loss": 1.607,
24
+ "step": 200
25
+ },
26
+ {
27
+ "epoch": 0.02021018593371059,
28
+ "grad_norm": 0.5963013172149658,
29
+ "learning_rate": 0.0009997429332697315,
30
+ "loss": 1.2186,
31
+ "step": 300
32
+ },
33
+ {
34
+ "epoch": 0.026946914578280787,
35
+ "grad_norm": 0.46841374039649963,
36
+ "learning_rate": 0.0009992860345329128,
37
+ "loss": 1.0664,
38
+ "step": 400
39
+ },
40
+ {
41
+ "epoch": 0.03368364322285099,
42
+ "grad_norm": 0.44179075956344604,
43
+ "learning_rate": 0.0009986009474597423,
44
+ "loss": 1.0087,
45
+ "step": 500
46
+ },
47
+ {
48
+ "epoch": 0.03368364322285099,
49
+ "eval_loss": 0.919044017791748,
50
+ "eval_runtime": 4.0503,
51
+ "eval_samples_per_second": 1234.464,
52
+ "eval_steps_per_second": 19.505,
53
+ "step": 500
54
+ },
55
+ {
56
+ "epoch": 0.04042037186742118,
57
+ "grad_norm": 0.396930456161499,
58
+ "learning_rate": 0.0009976879851550707,
59
+ "loss": 0.9759,
60
+ "step": 600
61
+ },
62
+ {
63
+ "epoch": 0.04715710051199138,
64
+ "grad_norm": 0.39025160670280457,
65
+ "learning_rate": 0.0009965475648694023,
66
+ "loss": 0.9506,
67
+ "step": 700
68
+ },
69
+ {
70
+ "epoch": 0.05389382915656157,
71
+ "grad_norm": 0.3577525317668915,
72
+ "learning_rate": 0.0009951802078081975,
73
+ "loss": 0.9323,
74
+ "step": 800
75
+ },
76
+ {
77
+ "epoch": 0.060630557801131774,
78
+ "grad_norm": 0.3586902618408203,
79
+ "learning_rate": 0.0009935865388936683,
80
+ "loss": 0.9148,
81
+ "step": 900
82
+ },
83
+ {
84
+ "epoch": 0.06736728644570197,
85
+ "grad_norm": 0.3558438718318939,
86
+ "learning_rate": 0.0009917672864791695,
87
+ "loss": 0.8993,
88
+ "step": 1000
89
+ },
90
+ {
91
+ "epoch": 0.06736728644570197,
92
+ "eval_loss": 0.8303639888763428,
93
+ "eval_runtime": 4.0434,
94
+ "eval_samples_per_second": 1236.578,
95
+ "eval_steps_per_second": 19.538,
96
+ "step": 1000
97
+ },
98
+ {
99
+ "epoch": 0.07410401509027216,
100
+ "grad_norm": 0.33415552973747253,
101
+ "learning_rate": 0.0009897232820163203,
102
+ "loss": 0.887,
103
+ "step": 1100
104
+ },
105
+ {
106
+ "epoch": 0.08084074373484236,
107
+ "grad_norm": 0.3328455686569214,
108
+ "learning_rate": 0.0009874554596750068,
109
+ "loss": 0.8764,
110
+ "step": 1200
111
+ },
112
+ {
113
+ "epoch": 0.08757747237941256,
114
+ "grad_norm": 0.34494221210479736,
115
+ "learning_rate": 0.000984964855916438,
116
+ "loss": 0.8687,
117
+ "step": 1300
118
+ },
119
+ {
120
+ "epoch": 0.09431420102398276,
121
+ "grad_norm": 0.3205359876155853,
122
+ "learning_rate": 0.0009822526090194543,
123
+ "loss": 0.8616,
124
+ "step": 1400
125
+ },
126
+ {
127
+ "epoch": 0.10105092966855295,
128
+ "grad_norm": 0.31778866052627563,
129
+ "learning_rate": 0.0009793199585602988,
130
+ "loss": 0.8531,
131
+ "step": 1500
132
+ },
133
+ {
134
+ "epoch": 0.10105092966855295,
135
+ "eval_loss": 0.7877992391586304,
136
+ "eval_runtime": 4.0459,
137
+ "eval_samples_per_second": 1235.828,
138
+ "eval_steps_per_second": 19.526,
139
+ "step": 1500
140
+ },
141
+ {
142
+ "epoch": 0.10778765831312315,
143
+ "grad_norm": 0.2896178066730499,
144
+ "learning_rate": 0.0009761682448460969,
145
+ "loss": 0.845,
146
+ "step": 1600
147
+ },
148
+ {
149
+ "epoch": 0.11452438695769335,
150
+ "grad_norm": 0.30994096398353577,
151
+ "learning_rate": 0.0009727989083022944,
152
+ "loss": 0.8422,
153
+ "step": 1700
154
+ },
155
+ {
156
+ "epoch": 0.12126111560226355,
157
+ "grad_norm": 0.2902910113334656,
158
+ "learning_rate": 0.0009692134888143424,
159
+ "loss": 0.8343,
160
+ "step": 1800
161
+ },
162
+ {
163
+ "epoch": 0.12799784424683375,
164
+ "grad_norm": 0.30568113923072815,
165
+ "learning_rate": 0.0009654136250239245,
166
+ "loss": 0.8302,
167
+ "step": 1900
168
+ },
169
+ {
170
+ "epoch": 0.13473457289140395,
171
+ "grad_norm": 0.2924252152442932,
172
+ "learning_rate": 0.0009614010535800489,
173
+ "loss": 0.8237,
174
+ "step": 2000
175
+ },
176
+ {
177
+ "epoch": 0.13473457289140395,
178
+ "eval_loss": 0.7636091113090515,
179
+ "eval_runtime": 4.0523,
180
+ "eval_samples_per_second": 1233.862,
181
+ "eval_steps_per_second": 19.495,
182
+ "step": 2000
183
+ },
184
+ {
185
+ "epoch": 0.14147130153597412,
186
+ "grad_norm": 0.2940412163734436,
187
+ "learning_rate": 0.0009571776083453492,
188
+ "loss": 0.8196,
189
+ "step": 2100
190
+ },
191
+ {
192
+ "epoch": 0.14820803018054432,
193
+ "grad_norm": 0.2964770495891571,
194
+ "learning_rate": 0.0009527452195579558,
195
+ "loss": 0.8155,
196
+ "step": 2200
197
+ },
198
+ {
199
+ "epoch": 0.15494475882511452,
200
+ "grad_norm": 0.29473844170570374,
201
+ "learning_rate": 0.0009481059129493202,
202
+ "loss": 0.8126,
203
+ "step": 2300
204
+ },
205
+ {
206
+ "epoch": 0.16168148746968472,
207
+ "grad_norm": 0.26849669218063354,
208
+ "learning_rate": 0.0009432618088183964,
209
+ "loss": 0.81,
210
+ "step": 2400
211
+ },
212
+ {
213
+ "epoch": 0.16841821611425492,
214
+ "grad_norm": 0.30280986428260803,
215
+ "learning_rate": 0.0009382151210626026,
216
+ "loss": 0.8071,
217
+ "step": 2500
218
+ },
219
+ {
220
+ "epoch": 0.16841821611425492,
221
+ "eval_loss": 0.7478171586990356,
222
+ "eval_runtime": 4.0503,
223
+ "eval_samples_per_second": 1234.482,
224
+ "eval_steps_per_second": 19.505,
225
+ "step": 2500
226
+ },
227
+ {
228
+ "epoch": 0.17515494475882512,
229
+ "grad_norm": 0.31329289078712463,
230
+ "learning_rate": 0.0009329681561660051,
231
+ "loss": 0.8021,
232
+ "step": 2600
233
+ },
234
+ {
235
+ "epoch": 0.18189167340339532,
236
+ "grad_norm": 0.2696886360645294,
237
+ "learning_rate": 0.0009275233121451872,
238
+ "loss": 0.8008,
239
+ "step": 2700
240
+ },
241
+ {
242
+ "epoch": 0.18862840204796552,
243
+ "grad_norm": 0.26912084221839905,
244
+ "learning_rate": 0.0009218830774532855,
245
+ "loss": 0.7973,
246
+ "step": 2800
247
+ },
248
+ {
249
+ "epoch": 0.1953651306925357,
250
+ "grad_norm": 0.27081477642059326,
251
+ "learning_rate": 0.0009160500298426945,
252
+ "loss": 0.7935,
253
+ "step": 2900
254
+ },
255
+ {
256
+ "epoch": 0.2021018593371059,
257
+ "grad_norm": 0.27368906140327454,
258
+ "learning_rate": 0.0009100268351869579,
259
+ "loss": 0.7908,
260
+ "step": 3000
261
+ },
262
+ {
263
+ "epoch": 0.2021018593371059,
264
+ "eval_loss": 0.7335129976272583,
265
+ "eval_runtime": 4.0548,
266
+ "eval_samples_per_second": 1233.113,
267
+ "eval_steps_per_second": 19.483,
268
+ "step": 3000
269
+ },
270
+ {
271
+ "epoch": 0.2088385879816761,
272
+ "grad_norm": 0.32002657651901245,
273
+ "learning_rate": 0.0009038162462623858,
274
+ "loss": 0.787,
275
+ "step": 3100
276
+ },
277
+ {
278
+ "epoch": 0.2155753166262463,
279
+ "grad_norm": 0.25296279788017273,
280
+ "learning_rate": 0.0008974211014899564,
281
+ "loss": 0.7873,
282
+ "step": 3200
283
+ },
284
+ {
285
+ "epoch": 0.2223120452708165,
286
+ "grad_norm": 0.27432960271835327,
287
+ "learning_rate": 0.0008908443236380743,
288
+ "loss": 0.7827,
289
+ "step": 3300
290
+ },
291
+ {
292
+ "epoch": 0.2290487739153867,
293
+ "grad_norm": 0.2552671730518341,
294
+ "learning_rate": 0.0008840889184867782,
295
+ "loss": 0.7793,
296
+ "step": 3400
297
+ },
298
+ {
299
+ "epoch": 0.2357855025599569,
300
+ "grad_norm": 0.27509957551956177,
301
+ "learning_rate": 0.0008771579734540138,
302
+ "loss": 0.7781,
303
+ "step": 3500
304
+ },
305
+ {
306
+ "epoch": 0.2357855025599569,
307
+ "eval_loss": 0.7217926383018494,
308
+ "eval_runtime": 4.0438,
309
+ "eval_samples_per_second": 1236.453,
310
+ "eval_steps_per_second": 19.536,
311
+ "step": 3500
312
+ },
313
+ {
314
+ "epoch": 0.2425222312045271,
315
+ "grad_norm": 0.25811567902565,
316
+ "learning_rate": 0.0008700546561845919,
317
+ "loss": 0.7764,
318
+ "step": 3600
319
+ },
320
+ {
321
+ "epoch": 0.24925895984909727,
322
+ "grad_norm": 0.26611506938934326,
323
+ "learning_rate": 0.000862782213102482,
324
+ "loss": 0.7744,
325
+ "step": 3700
326
+ },
327
+ {
328
+ "epoch": 0.2559956884936675,
329
+ "grad_norm": 0.2390570193529129,
330
+ "learning_rate": 0.0008553439679271025,
331
+ "loss": 0.7717,
332
+ "step": 3800
333
+ },
334
+ {
335
+ "epoch": 0.2627324171382377,
336
+ "grad_norm": 0.26289165019989014,
337
+ "learning_rate": 0.0008477433201542824,
338
+ "loss": 0.769,
339
+ "step": 3900
340
+ },
341
+ {
342
+ "epoch": 0.2694691457828079,
343
+ "grad_norm": 0.2603146731853485,
344
+ "learning_rate": 0.0008399837435025926,
345
+ "loss": 0.7658,
346
+ "step": 4000
347
+ },
348
+ {
349
+ "epoch": 0.2694691457828079,
350
+ "eval_loss": 0.7102092504501343,
351
+ "eval_runtime": 4.0458,
352
+ "eval_samples_per_second": 1235.853,
353
+ "eval_steps_per_second": 19.526,
354
+ "step": 4000
355
+ }
356
+ ],
357
+ "logging_steps": 100,
358
+ "max_steps": 14844,
359
+ "num_input_tokens_seen": 0,
360
+ "num_train_epochs": 1,
361
+ "save_steps": 500,
362
+ "stateful_callbacks": {
363
+ "TrainerControl": {
364
+ "args": {
365
+ "should_epoch_stop": false,
366
+ "should_evaluate": false,
367
+ "should_log": false,
368
+ "should_save": true,
369
+ "should_training_stop": false
370
+ },
371
+ "attributes": {}
372
+ }
373
+ },
374
+ "total_flos": 493989888000000.0,
375
+ "train_batch_size": 64,
376
+ "trial_name": null,
377
+ "trial_params": null
378
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:554c8d7f2ee5a566a96af9e0c7c3aab64f9364723061d79d555fa187b12ef08d
3
+ size 5777
vocab.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ " ": 4,
7
+ "BB": 5,
8
+ "BK": 6,
9
+ "BN": 7,
10
+ "BP": 8,
11
+ "BQ": 9,
12
+ "BR": 10,
13
+ "WB": 11,
14
+ "WK": 12,
15
+ "WN": 13,
16
+ "WP": 14,
17
+ "WQ": 15,
18
+ "WR": 16,
19
+ "a1": 17,
20
+ "a2": 18,
21
+ "a3": 19,
22
+ "a4": 20,
23
+ "a5": 21,
24
+ "a6": 22,
25
+ "a7": 23,
26
+ "a8": 24,
27
+ "b1": 25,
28
+ "b2": 26,
29
+ "b3": 27,
30
+ "b4": 28,
31
+ "b5": 29,
32
+ "b6": 30,
33
+ "b7": 31,
34
+ "b8": 32,
35
+ "c1": 33,
36
+ "c2": 34,
37
+ "c3": 35,
38
+ "c4": 36,
39
+ "c5": 37,
40
+ "c6": 38,
41
+ "c7": 39,
42
+ "c8": 40,
43
+ "d1": 41,
44
+ "d2": 42,
45
+ "d3": 43,
46
+ "d4": 44,
47
+ "d5": 45,
48
+ "d6": 46,
49
+ "d7": 47,
50
+ "d8": 48,
51
+ "e1": 49,
52
+ "e2": 50,
53
+ "e3": 51,
54
+ "e4": 52,
55
+ "e5": 53,
56
+ "e6": 54,
57
+ "e7": 55,
58
+ "e8": 56,
59
+ "f1": 57,
60
+ "f2": 58,
61
+ "f3": 59,
62
+ "f4": 60,
63
+ "f5": 61,
64
+ "f6": 62,
65
+ "f7": 63,
66
+ "f8": 64,
67
+ "g1": 65,
68
+ "g2": 66,
69
+ "g3": 67,
70
+ "g4": 68,
71
+ "g5": 69,
72
+ "g6": 70,
73
+ "g7": 71,
74
+ "g8": 72,
75
+ "h1": 73,
76
+ "h2": 74,
77
+ "h3": 75,
78
+ "h4": 76,
79
+ "h5": 77,
80
+ "h6": 78,
81
+ "h7": 79,
82
+ "h8": 80
83
+ }