graug commited on
Commit
d1476a5
·
verified ·
1 Parent(s): 8d4b034

Chess Challenge submission by graug

Browse files
Files changed (8) hide show
  1. README.md +26 -0
  2. config.json +24 -0
  3. model.py +598 -0
  4. model.safetensors +3 -0
  5. special_tokens_map.json +6 -0
  6. tokenizer.py +365 -0
  7. tokenizer_config.json +50 -0
  8. vocab.json +74 -0
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - chess
5
+ - llm-course
6
+ - chess-challenge
7
+ license: mit
8
+ ---
9
+
10
+ # chess_clarelec_3
11
+
12
+ Chess model submitted to the LLM Course Chess Challenge.
13
+
14
+ ## Submission Info
15
+
16
+ - **Submitted by**: [graug](https://huggingface.co/graug)
17
+ - **Parameters**: 869,120
18
+ - **Organization**: LLM-course
19
+
20
+ ## Model Details
21
+
22
+ - **Architecture**: Chess Transformer (GPT-style)
23
+ - **Vocab size**: 72
24
+ - **Embedding dim**: 128
25
+ - **Layers**: 5
26
+ - **Heads**: 8
config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ChessForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "model.ChessConfig",
7
+ "AutoModelForCausalLM": "model.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": 128,
17
+ "n_head": 8,
18
+ "n_inner": 384,
19
+ "n_layer": 5,
20
+ "pad_token_id": 0,
21
+ "tie_weights": true,
22
+ "transformers_version": "4.57.5",
23
+ "vocab_size": 72
24
+ }
model.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 MixtureOfExperts(nn.Module):
219
+ """Sparse Mixture of Experts Layer"""
220
+
221
+ def __init__(self, config: ChessConfig, n_experts: int = 4, top_k: int = 2):
222
+ super().__init__()
223
+
224
+ self.n_experts = n_experts
225
+ self.top_k = top_k
226
+ self.experts = nn.ModuleList([
227
+ FeedForward(config) for _ in range(n_experts)
228
+ ])
229
+ self.gate = nn.Linear(config.n_embd, n_experts)
230
+
231
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
232
+ batch_size, seq_len, n_embd = x.size()
233
+
234
+ # Compute gating scores
235
+ gate_logits = self.gate(x) # (batch_size, seq_len, n_experts)
236
+ gate_scores = F.softmax(gate_logits, dim=-1)
237
+
238
+ # Select top-k experts
239
+ top_k_scores, top_k_indices = torch.topk(gate_scores, self.top_k, dim=-1)
240
+
241
+ # Renormalize scores
242
+ top_k_scores = top_k_scores / top_k_scores.sum(dim=-1, keepdim=True)
243
+
244
+ # Initialize output
245
+ output = torch.zeros_like(x)
246
+
247
+ # Compute only selected expert outputs
248
+ for k in range(self.top_k):
249
+ expert_idx = top_k_indices[..., k] # (batch_size, seq_len)
250
+ score = top_k_scores[..., k:k+1] # (batch_size, seq_len, 1)
251
+
252
+ for e in range(self.n_experts):
253
+ mask = (expert_idx == e)
254
+ if mask.any():
255
+ expert_input = x[mask]
256
+ expert_output = self.experts[e](expert_input)
257
+ output[mask] += score[mask].squeeze(-1).unsqueeze(-1) * expert_output
258
+
259
+ return output
260
+
261
+ class MultiHeadLatentAttention(nn.Module):
262
+
263
+ def __init__(self, config: ChessConfig):
264
+ super().__init__()
265
+
266
+ assert config.n_embd % config.n_head == 0, \
267
+ f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
268
+
269
+ self.n_head = config.n_head
270
+ self.n_embd = config.n_embd
271
+ self.head_dim = config.n_embd // config.n_head
272
+ self.latent_dim = config.n_embd//2 # You can adjust this as needed
273
+
274
+ # Combined QKV projection for efficiency
275
+ self.c_attn = nn.Linear(config.n_embd, config.n_embd + self.latent_dim)
276
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
277
+
278
+ self.c_value_key = nn.Linear(self.latent_dim, 2 * config.n_embd)
279
+
280
+ self.dropout = nn.Dropout(config.dropout)
281
+
282
+
283
+ # Causal mask (will be created on first forward pass)
284
+ self.register_buffer(
285
+ "bias",
286
+ torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
287
+ 1, 1, config.n_ctx, config.n_ctx
288
+ ),
289
+ persistent=False,
290
+ )
291
+
292
+ def forward(
293
+ self,
294
+ x: torch.Tensor,
295
+ attention_mask: Optional[torch.Tensor] = None,
296
+ ) -> torch.Tensor:
297
+ batch_size, seq_len, _ = x.size()
298
+
299
+
300
+
301
+
302
+ # Compute Q, K, V
303
+ qkv = self.c_attn(x)
304
+ q, kv = qkv.split(self.n_embd, dim=2)
305
+
306
+
307
+
308
+
309
+ kv = self.c_value_key(kv)
310
+
311
+ k,v = kv.split(self.n_embd, dim=2)
312
+
313
+ # Reshape for multi-head attention
314
+ q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
315
+ k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
316
+ v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
317
+
318
+ # Scaled dot-product attention
319
+ attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
320
+
321
+ # Apply causal mask
322
+ causal_mask = self.bias[:, :, :seq_len, :seq_len]
323
+ attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
324
+
325
+ # Apply attention mask (for padding)
326
+ if attention_mask is not None:
327
+ # attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
328
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
329
+ attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
330
+
331
+ attn_weights = F.softmax(attn_weights, dim=-1)
332
+ attn_weights = self.dropout(attn_weights)
333
+
334
+ # Apply attention to values
335
+ attn_output = torch.matmul(attn_weights, v)
336
+
337
+ # Reshape back
338
+ attn_output = attn_output.transpose(1, 2).contiguous().view(
339
+ batch_size, seq_len, self.n_embd
340
+ )
341
+
342
+ # Output projection
343
+ attn_output = self.c_proj(attn_output)
344
+
345
+ return attn_output
346
+
347
+
348
+
349
+ class DeepSeekTransformer(PreTrainedModel):
350
+ """a single transformer blocks from Deepseek R3 model
351
+
352
+
353
+ """
354
+
355
+ def __init__(self, config: ChessConfig):
356
+ super().__init__(config)
357
+
358
+ self.ln_1 = nn.RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
359
+ self.attn = MultiHeadAttention(config)
360
+ self.ln_2 = nn.RMSNorm(config.n_embd, eps=config.layer_norm_epsilon)
361
+ self.mlp = MixtureOfExperts(config)
362
+
363
+
364
+ self.post_init()
365
+
366
+ def forward(
367
+ self,
368
+ x: torch.Tensor,
369
+ attention_mask: Optional[torch.Tensor] = None,
370
+ ) -> torch.Tensor:
371
+ # Pre-norm attention
372
+ x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
373
+ # Pre-norm FFN
374
+ x = x + self.mlp(self.ln_2(x))
375
+ return x
376
+
377
+
378
+ class ChessForCausalLM(PreTrainedModel):
379
+ """
380
+ Chess Transformer for Causal Language Modeling (next-move prediction).
381
+
382
+ This model is designed to predict the next chess move given a sequence
383
+ of previous moves. It uses a GPT-style architecture with:
384
+ - Token embeddings for chess moves
385
+ - Learned positional embeddings
386
+ - Stacked transformer blocks
387
+ - Linear head for next-token prediction
388
+
389
+ The model supports weight tying between the embedding layer and the
390
+ output projection to save parameters.
391
+
392
+ Example:
393
+ >>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
394
+ >>> model = ChessForCausalLM(config)
395
+ >>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
396
+ >>> outputs = model(**inputs)
397
+ >>> next_move_logits = outputs.logits[:, -1, :]
398
+ """
399
+
400
+ config_class = ChessConfig
401
+ base_model_prefix = "transformer"
402
+ supports_gradient_checkpointing = True
403
+ # Suppress missing-key warning for tied lm_head when loading
404
+ keys_to_ignore_on_load_missing = ["lm_head.weight"]
405
+
406
+ def __init__(self, config: ChessConfig):
407
+ super().__init__(config)
408
+
409
+ # Token and position embeddings
410
+ self.wte = nn.Embedding(config.vocab_size, config.n_embd)
411
+ self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
412
+
413
+ self.drop = nn.Dropout(config.dropout)
414
+
415
+ # Transformer blocks
416
+ self.h = nn.ModuleList([
417
+ TransformerBlock(config) for _ in range(config.n_layer)
418
+ ])
419
+
420
+ # Final layer norm
421
+ self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
422
+
423
+ # Output head
424
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
425
+
426
+ # Declare tied weights for proper serialization
427
+ if config.tie_weights:
428
+ self._tied_weights_keys = ["lm_head.weight"]
429
+
430
+ # Initialize weights
431
+ self.post_init()
432
+
433
+ # Tie weights if configured
434
+ if config.tie_weights:
435
+ self.tie_weights()
436
+
437
+ def get_input_embeddings(self) -> nn.Module:
438
+ return self.wte
439
+
440
+ def set_input_embeddings(self, new_embeddings: nn.Module):
441
+ self.wte = new_embeddings
442
+ if getattr(self.config, "tie_weights", False):
443
+ self.tie_weights()
444
+
445
+ def get_output_embeddings(self) -> nn.Module:
446
+ return self.lm_head
447
+
448
+ def set_output_embeddings(self, new_embeddings: nn.Module):
449
+ self.lm_head = new_embeddings
450
+
451
+ def tie_weights(self):
452
+ # Use HF helper to tie or clone depending on config
453
+ if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
454
+ self._tie_or_clone_weights(self.lm_head, self.wte)
455
+
456
+ def _init_weights(self, module: nn.Module):
457
+ """Initialize weights following GPT-2 style."""
458
+ if isinstance(module, nn.Linear):
459
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
460
+ if module.bias is not None:
461
+ torch.nn.init.zeros_(module.bias)
462
+ elif isinstance(module, nn.Embedding):
463
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
464
+ elif isinstance(module, nn.LayerNorm):
465
+ torch.nn.init.ones_(module.weight)
466
+ torch.nn.init.zeros_(module.bias)
467
+
468
+ def forward(
469
+ self,
470
+ input_ids: torch.LongTensor,
471
+ attention_mask: Optional[torch.Tensor] = None,
472
+ position_ids: Optional[torch.LongTensor] = None,
473
+ labels: Optional[torch.LongTensor] = None,
474
+ return_dict: Optional[bool] = None,
475
+ **kwargs,
476
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
477
+ """
478
+ Forward pass of the model.
479
+
480
+ Args:
481
+ input_ids: Token IDs of shape (batch_size, seq_len).
482
+ attention_mask: Attention mask of shape (batch_size, seq_len).
483
+ position_ids: Position IDs of shape (batch_size, seq_len).
484
+ labels: Labels for language modeling loss.
485
+ return_dict: Whether to return a ModelOutput object.
486
+
487
+ Returns:
488
+ CausalLMOutputWithPast containing loss (if labels provided) and logits.
489
+ """
490
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
491
+
492
+ batch_size, seq_len = input_ids.size()
493
+ device = input_ids.device
494
+
495
+ # Create position IDs if not provided
496
+ if position_ids is None:
497
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
498
+
499
+ # Get embeddings
500
+ token_embeds = self.wte(input_ids)
501
+ position_embeds = self.wpe(position_ids)
502
+ hidden_states = self.drop(token_embeds + position_embeds)
503
+
504
+ # Pass through transformer blocks
505
+ for block in self.h:
506
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
507
+
508
+ # Final layer norm
509
+ hidden_states = self.ln_f(hidden_states)
510
+
511
+ # Get logits
512
+ logits = self.lm_head(hidden_states)
513
+
514
+ # Compute loss if labels are provided
515
+ loss = None
516
+ if labels is not None:
517
+ # Shift logits and labels for next-token prediction
518
+ shift_logits = logits[..., :-1, :].contiguous()
519
+ shift_labels = labels[..., 1:].contiguous()
520
+
521
+ # Flatten for cross-entropy
522
+ # Use -100 as ignore_index (standard convention for masked labels)
523
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
524
+ loss = loss_fct(
525
+ shift_logits.view(-1, shift_logits.size(-1)),
526
+ shift_labels.view(-1),
527
+ )
528
+
529
+ if not return_dict:
530
+ output = (logits,)
531
+ return ((loss,) + output) if loss is not None else output
532
+
533
+ return CausalLMOutputWithPast(
534
+ loss=loss,
535
+ logits=logits,
536
+ past_key_values=None,
537
+ hidden_states=None,
538
+ attentions=None,
539
+ )
540
+
541
+ @torch.no_grad()
542
+ def generate_move(
543
+ self,
544
+ input_ids: torch.LongTensor,
545
+ temperature: float = 1.0,
546
+ top_k: Optional[int] = None,
547
+ top_p: Optional[float] = None,
548
+ ) -> int:
549
+ """
550
+ Generate the next move given a sequence of moves.
551
+
552
+ Args:
553
+ input_ids: Token IDs of shape (1, seq_len).
554
+ temperature: Sampling temperature (1.0 = no change).
555
+ top_k: If set, only sample from top k tokens.
556
+ top_p: If set, use nucleus sampling with this threshold.
557
+
558
+ Returns:
559
+ The token ID of the predicted next move.
560
+ """
561
+ self.eval()
562
+
563
+ # Get logits for the last position
564
+ outputs = self(input_ids)
565
+ logits = outputs.logits[:, -1, :] / temperature
566
+
567
+ # Apply top-k filtering
568
+ if top_k is not None:
569
+ indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
570
+ logits[indices_to_remove] = float("-inf")
571
+
572
+ # Apply top-p (nucleus) filtering
573
+ if top_p is not None:
574
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
575
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
576
+
577
+ # Remove tokens with cumulative probability above the threshold
578
+ sorted_indices_to_remove = cumulative_probs > top_p
579
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
580
+ sorted_indices_to_remove[..., 0] = 0
581
+
582
+ indices_to_remove = sorted_indices_to_remove.scatter(
583
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
584
+ )
585
+ logits[indices_to_remove] = float("-inf")
586
+
587
+ # Sample from the distribution
588
+ probs = F.softmax(logits, dim=-1)
589
+ next_token = torch.multinomial(probs, num_samples=1)
590
+
591
+ return next_token.item()
592
+
593
+
594
+ # Register the model with Auto classes for easy loading
595
+ from transformers import AutoConfig, AutoModelForCausalLM
596
+
597
+ AutoConfig.register("chess_transformer", ChessConfig)
598
+ AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdc9bf529f50fb59a4fcb654a6a524844ce3bde9c2499bc63100ca33c7a53f38
3
+ size 3481904
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,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
25
+ class ChessTokenizer(PreTrainedTokenizer):
26
+ """
27
+ A custom tokenizer for chess moves using extended UCI notation.
28
+
29
+ This tokenizer maps each possible chess move to a unique token ID.
30
+ The vocabulary is built from the training dataset to ensure all moves
31
+ encountered during training have a corresponding token.
32
+
33
+ Example:
34
+ >>> tokenizer = ChessTokenizer()
35
+ >>> tokenizer.encode("WPe2e4 BPe7e5")
36
+ [1, 42, 87, 2] # [BOS, e2e4, e7e5, EOS]
37
+ """
38
+
39
+ model_input_names = ["input_ids", "attention_mask"]
40
+ vocab_files_names = {"vocab_file": "vocab.json"}
41
+
42
+ # Special tokens
43
+ PAD_TOKEN = "[PAD]"
44
+ BOS_TOKEN = "[BOS]"
45
+ EOS_TOKEN = "[EOS]"
46
+ UNK_TOKEN = "[UNK]"
47
+
48
+ def __init__(
49
+ self,
50
+ vocab_file: Optional[str] = None,
51
+ vocab: Optional[Dict[str, int]] = None,
52
+ **kwargs,
53
+ ):
54
+ """
55
+ Initialize the chess tokenizer.
56
+
57
+ Args:
58
+ vocab_file: Path to a JSON file containing the vocabulary mapping.
59
+ vocab: Dictionary mapping tokens to IDs (alternative to vocab_file).
60
+ **kwargs: Additional arguments passed to PreTrainedTokenizer.
61
+ """
62
+ # Initialize special tokens
63
+ self._pad_token = self.PAD_TOKEN
64
+ self._bos_token = self.BOS_TOKEN
65
+ self._eos_token = self.EOS_TOKEN
66
+ self._unk_token = self.UNK_TOKEN
67
+
68
+ # Remove any duplicate special-token entries passed through kwargs
69
+ # to avoid "multiple values for keyword" errors when loading from disk.
70
+ kwargs.pop("pad_token", None)
71
+ kwargs.pop("bos_token", None)
72
+ kwargs.pop("eos_token", None)
73
+ kwargs.pop("unk_token", None)
74
+
75
+ # Load or create vocabulary
76
+ if vocab is not None:
77
+ self._vocab = vocab
78
+ elif vocab_file is not None and os.path.exists(vocab_file):
79
+ with open(vocab_file, "r", encoding="utf-8") as f:
80
+ self._vocab = json.load(f)
81
+ else:
82
+ # Create a minimal vocabulary with just special tokens
83
+ # The full vocabulary should be built from the dataset
84
+ self._vocab = self._create_default_vocab()
85
+
86
+ # Create reverse mapping
87
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
88
+
89
+ # Call parent init AFTER setting up vocab
90
+ super().__init__(
91
+ pad_token=self._pad_token,
92
+ bos_token=self._bos_token,
93
+ eos_token=self._eos_token,
94
+ unk_token=self._unk_token,
95
+ **kwargs,
96
+ )
97
+
98
+ def _create_default_vocab(self) -> Dict[str, int]:
99
+ """
100
+ Create a minimal default vocabulary with just special tokens.
101
+
102
+ For the full vocabulary, use `build_vocab_from_dataset()`.
103
+ This minimal vocab is just a placeholder - you should build from data.
104
+ """
105
+ special_tokens = [self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN]
106
+ vocab = {token: idx for idx, token in enumerate(special_tokens)}
107
+ return vocab
108
+
109
+ @classmethod
110
+ def build_vocab_from_iterator(
111
+ cls,
112
+ iterator,
113
+ min_frequency: int = 1,
114
+ ) -> "ChessTokenizer":
115
+ """
116
+ Build a tokenizer vocabulary from an iterator of game strings.
117
+
118
+ Args:
119
+ iterator: An iterator yielding game strings (space-separated moves).
120
+ min_frequency: Minimum frequency for a token to be included.
121
+
122
+ Returns:
123
+ A ChessTokenizer with the built vocabulary.
124
+ """
125
+ from collections import Counter
126
+
127
+ token_counts = Counter()
128
+
129
+ for game in iterator:
130
+ moves = game.strip().split()
131
+ token_counts.update(moves)
132
+
133
+ # Filter by frequency
134
+ tokens = [
135
+ token for token, count in token_counts.items()
136
+ if count >= min_frequency
137
+ ]
138
+
139
+ # Sort for reproducibility
140
+ tokens = sorted(tokens)
141
+
142
+ # Build vocabulary
143
+ special_tokens = [cls.PAD_TOKEN, cls.BOS_TOKEN, cls.EOS_TOKEN, cls.UNK_TOKEN]
144
+ vocab = {token: idx for idx, token in enumerate(special_tokens + tokens)}
145
+
146
+ return cls(vocab=vocab)
147
+
148
+ @classmethod
149
+ def build_vocab_from_dataset(
150
+ cls,
151
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
152
+ split: str = "train",
153
+ column: str = "text",
154
+ min_frequency: int = 500,
155
+ max_samples: Optional[int] = 100000,
156
+ ) -> "ChessTokenizer":
157
+ """
158
+ Build a tokenizer vocabulary from a Hugging Face dataset.
159
+
160
+ Args:
161
+ dataset_name: Name of the dataset on Hugging Face Hub.
162
+ split: Dataset split to use.
163
+ column: Column containing the game strings.
164
+ min_frequency: Minimum frequency for a token to be included (default: 500).
165
+ max_samples: Maximum number of samples to process (default: 100k).
166
+
167
+ Returns:
168
+ A ChessTokenizer with the built vocabulary.
169
+ """
170
+ from datasets import load_dataset
171
+
172
+ dataset = load_dataset(dataset_name, split=split)
173
+
174
+ if max_samples is not None:
175
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
176
+
177
+ def game_iterator():
178
+ for example in dataset:
179
+ yield example[column]
180
+
181
+ return cls.build_vocab_from_iterator(game_iterator(), min_frequency=min_frequency)
182
+
183
+ @classmethod
184
+ def build_vocab_uci(cls):
185
+
186
+
187
+ files = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
188
+ ranks = ['1', '2', '3', '4', '5', '6', '7', '8']
189
+
190
+ cases = []
191
+ for file in files:
192
+ for rank in ranks:
193
+ cases.append(f"{file}{rank}")
194
+
195
+ vocab_list = cases
196
+
197
+ promotion_pieces = ['n', 'b', 'r', 'q']
198
+ vocab_list += promotion_pieces
199
+ return cls.build_vocab_from_iterator(vocab_list)
200
+
201
+
202
+
203
+ @property
204
+ def vocab_size(self) -> int:
205
+ """Return the size of the vocabulary."""
206
+ return len(self._vocab)
207
+
208
+ def get_vocab(self) -> Dict[str, int]:
209
+ """Return the vocabulary as a dictionary."""
210
+ return dict(self._vocab)
211
+
212
+ def _tokenize(self, text: str) -> List[str]:
213
+ """
214
+ Tokenize a string of moves into a list of tokens.
215
+
216
+ Each move is split into 3 tokens: Piece + from_square + to_square
217
+ Example: "WPe2e4" -> ["P", "e2", "e4"]
218
+
219
+ Args:
220
+ text: A string of space-separated moves.
221
+
222
+ Returns:
223
+ List of tokens (piece letters and squares).
224
+ """
225
+ words = text.strip().split()
226
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
227
+
228
+ tokens = []
229
+ for word in words:
230
+ # Keep special tokens as-is
231
+ if word in special:
232
+ tokens.append(word)
233
+ continue
234
+
235
+ # Remove W/B color prefix
236
+ if len(word) > 0 and word[0] in 'WB':
237
+ move = word[1:]
238
+ else:
239
+ move = word
240
+ #remove piece
241
+ if word[1] in 'PNBRQK':
242
+ move = move[1:]
243
+
244
+
245
+ # Remove suffixes like (x), (+), (+*), (o), (O)
246
+ for symbol in ['(x+*)', '(x+)', '(x)', '(+*)', '(+)', '(o)', '(O)']:
247
+ move = move.replace(symbol, '')
248
+
249
+ # address promotion
250
+ if '=' in move:
251
+ moves = move.split('=')
252
+ move = moves[0]
253
+ promotion_piece = moves[1]
254
+ # mettre la piece de promotion e minuscule
255
+ promotion_piece = promotion_piece.lower()
256
+
257
+ move += promotion_piece
258
+
259
+
260
+
261
+ # Now move should be in format from_square + to_square (e.g., e2e4)
262
+ if len(move) == 4:
263
+ from_sq = move[:2]
264
+ to_sq = move[2:]
265
+ tokens.extend([from_sq, to_sq])
266
+
267
+ if len(move) == 5:
268
+ from_sq = move[:2]
269
+ to_sq = move[2:4]
270
+ promotion_piece = move[4]
271
+ tokens.extend([from_sq, to_sq, promotion_piece])
272
+ return tokens
273
+
274
+
275
+
276
+ def _convert_token_to_id(self, token: str) -> int:
277
+ """Convert a token to its ID."""
278
+ return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
279
+
280
+ def _convert_id_to_token(self, index: int) -> str:
281
+ """Convert an ID to its token."""
282
+ return self._ids_to_tokens.get(index, self.UNK_TOKEN)
283
+
284
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
285
+ """Convert a list of tokens back to a string."""
286
+ # Filter out special tokens for cleaner output
287
+ special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN}
288
+
289
+ tokens = [t for t in tokens if t not in special]
290
+
291
+ #Grouper les tokens par 2 (from_square, to_square) ou 3 (from_square, to_square, promotion_piece)
292
+ grouped_tokens = []
293
+ i = 0
294
+ while i < len(tokens):
295
+ if i + 2 < len(tokens) and tokens[i+2] in ['n', 'b', 'r', 'q']:
296
+ grouped_tokens.append("".join(tokens[i:i+3]))
297
+ i += 3
298
+ else:
299
+ grouped_tokens.append("".join(tokens[i:i+2]))
300
+ i += 2
301
+
302
+ return " ".join(grouped_tokens)
303
+
304
+ def save_vocabulary(
305
+ self,
306
+ save_directory: str,
307
+ filename_prefix: Optional[str] = None,
308
+ ) -> tuple:
309
+ """
310
+ Save the vocabulary to a JSON file.
311
+
312
+ Args:
313
+ save_directory: Directory to save the vocabulary.
314
+ filename_prefix: Optional prefix for the filename.
315
+
316
+ Returns:
317
+ Tuple containing the path to the saved vocabulary file.
318
+ """
319
+ if not os.path.isdir(save_directory):
320
+ os.makedirs(save_directory, exist_ok=True)
321
+
322
+ vocab_file = os.path.join(
323
+ save_directory,
324
+ (filename_prefix + "-" if filename_prefix else "") + "vocab.json",
325
+ )
326
+
327
+ with open(vocab_file, "w", encoding="utf-8") as f:
328
+ json.dump(self._vocab, f, ensure_ascii=False, indent=2)
329
+
330
+ return (vocab_file,)
331
+
332
+
333
+ def count_vocab_from_dataset(
334
+ dataset_name: str = "dlouapre/lichess_2025-01_1M",
335
+ split: str = "train",
336
+ column: str = "text",
337
+ max_samples: Optional[int] = 10000,
338
+ ) -> Dict[str, int]:
339
+ """
340
+ Count token frequencies in a dataset (useful for vocabulary analysis).
341
+
342
+ Args:
343
+ dataset_name: Name of the dataset on Hugging Face Hub.
344
+ split: Dataset split to use.
345
+ column: Column containing the game strings.
346
+ max_samples: Maximum number of samples to process.
347
+
348
+ Returns:
349
+ Dictionary mapping tokens to their frequencies.
350
+ """
351
+ from collections import Counter
352
+ from datasets import load_dataset
353
+
354
+ dataset = load_dataset(dataset_name, split=split)
355
+
356
+ if max_samples is not None:
357
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
358
+
359
+ token_counts = Counter()
360
+
361
+ for example in dataset:
362
+ moves = example[column].strip().split()
363
+ token_counts.update(moves)
364
+
365
+ 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
+ }
vocab.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[BOS]": 1,
4
+ "[EOS]": 2,
5
+ "[UNK]": 3,
6
+ "a1": 4,
7
+ "a2": 5,
8
+ "a3": 6,
9
+ "a4": 7,
10
+ "a5": 8,
11
+ "a6": 9,
12
+ "a7": 10,
13
+ "a8": 11,
14
+ "b": 12,
15
+ "b1": 13,
16
+ "b2": 14,
17
+ "b3": 15,
18
+ "b4": 16,
19
+ "b5": 17,
20
+ "b6": 18,
21
+ "b7": 19,
22
+ "b8": 20,
23
+ "c1": 21,
24
+ "c2": 22,
25
+ "c3": 23,
26
+ "c4": 24,
27
+ "c5": 25,
28
+ "c6": 26,
29
+ "c7": 27,
30
+ "c8": 28,
31
+ "d1": 29,
32
+ "d2": 30,
33
+ "d3": 31,
34
+ "d4": 32,
35
+ "d5": 33,
36
+ "d6": 34,
37
+ "d7": 35,
38
+ "d8": 36,
39
+ "e1": 37,
40
+ "e2": 38,
41
+ "e3": 39,
42
+ "e4": 40,
43
+ "e5": 41,
44
+ "e6": 42,
45
+ "e7": 43,
46
+ "e8": 44,
47
+ "f1": 45,
48
+ "f2": 46,
49
+ "f3": 47,
50
+ "f4": 48,
51
+ "f5": 49,
52
+ "f6": 50,
53
+ "f7": 51,
54
+ "f8": 52,
55
+ "g1": 53,
56
+ "g2": 54,
57
+ "g3": 55,
58
+ "g4": 56,
59
+ "g5": 57,
60
+ "g6": 58,
61
+ "g7": 59,
62
+ "g8": 60,
63
+ "h1": 61,
64
+ "h2": 62,
65
+ "h3": 63,
66
+ "h4": 64,
67
+ "h5": 65,
68
+ "h6": 66,
69
+ "h7": 67,
70
+ "h8": 68,
71
+ "n": 69,
72
+ "q": 70,
73
+ "r": 71
74
+ }