Chess Challenge submission by swdo
Browse files- README.md +26 -0
- config.json +24 -0
- model.py +437 -0
- model.safetensors +3 -0
- special_tokens_map.json +6 -0
- tokenizer.py +398 -0
- tokenizer_config.json +11 -0
- vocab.json +90 -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_swdo_subTok
|
| 11 |
+
|
| 12 |
+
Chess model submitted to the LLM Course Chess Challenge.
|
| 13 |
+
|
| 14 |
+
## Submission Info
|
| 15 |
+
|
| 16 |
+
- **Submitted by**: [swdo](https://huggingface.co/swdo)
|
| 17 |
+
- **Parameters**: 705,792
|
| 18 |
+
- **Organization**: LLM-course
|
| 19 |
+
|
| 20 |
+
## Model Details
|
| 21 |
+
|
| 22 |
+
- **Architecture**: Chess Transformer (GPT-style)
|
| 23 |
+
- **Vocab size**: 88
|
| 24 |
+
- **Embedding dim**: 128
|
| 25 |
+
- **Layers**: 4
|
| 26 |
+
- **Heads**: 4
|
config.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"ChessForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"bos_token_id": 1,
|
| 6 |
+
"dropout": 0.1,
|
| 7 |
+
"dtype": "float32",
|
| 8 |
+
"eos_token_id": 2,
|
| 9 |
+
"layer_norm_epsilon": 1e-05,
|
| 10 |
+
"model_type": "chess_transformer",
|
| 11 |
+
"n_ctx": 256,
|
| 12 |
+
"n_embd": 128,
|
| 13 |
+
"n_head": 4,
|
| 14 |
+
"n_inner": 384,
|
| 15 |
+
"n_layer": 4,
|
| 16 |
+
"pad_token_id": 0,
|
| 17 |
+
"tie_weights": true,
|
| 18 |
+
"transformers_version": "4.57.3",
|
| 19 |
+
"vocab_size": 88,
|
| 20 |
+
"auto_map": {
|
| 21 |
+
"AutoConfig": "model.ChessConfig",
|
| 22 |
+
"AutoModelForCausalLM": "model.ChessForCausalLM"
|
| 23 |
+
}
|
| 24 |
+
}
|
model.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chess Transformer Model for the Chess Challenge.
|
| 3 |
+
|
| 4 |
+
This module provides a simple GPT-style transformer architecture
|
| 5 |
+
designed to fit within the 1M parameter constraint.
|
| 6 |
+
|
| 7 |
+
Key components:
|
| 8 |
+
- ChessConfig: Configuration class for model hyperparameters
|
| 9 |
+
- ChessForCausalLM: The main model class for next-move prediction
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import math
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 22 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ChessConfig(PretrainedConfig):
|
| 26 |
+
"""
|
| 27 |
+
Configuration class for the Chess Transformer model.
|
| 28 |
+
|
| 29 |
+
This configuration is designed for a ~1M parameter model.
|
| 30 |
+
Students can adjust these values to explore different architectures.
|
| 31 |
+
|
| 32 |
+
Parameter budget breakdown (with default values):
|
| 33 |
+
- Embeddings (vocab): 1200 x 128 = 153,600
|
| 34 |
+
- Position Embeddings: 256 x 128 = 32,768
|
| 35 |
+
- Transformer Layers: 6 x ~120,000 = ~720,000
|
| 36 |
+
- LM Head (with weight tying): 0 (shared with embeddings)
|
| 37 |
+
- Total: ~906,000 parameters
|
| 38 |
+
|
| 39 |
+
Attributes:
|
| 40 |
+
vocab_size: Size of the vocabulary (number of unique moves).
|
| 41 |
+
n_embd: Embedding dimension (d_model).
|
| 42 |
+
n_layer: Number of transformer layers.
|
| 43 |
+
n_head: Number of attention heads.
|
| 44 |
+
n_ctx: Maximum sequence length (context window).
|
| 45 |
+
n_inner: Feed-forward inner dimension (default: 3 * n_embd).
|
| 46 |
+
dropout: Dropout probability.
|
| 47 |
+
layer_norm_epsilon: Epsilon for layer normalization.
|
| 48 |
+
tie_weights: Whether to tie embedding and output weights.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
model_type = "chess_transformer"
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
vocab_size: int = 1200,
|
| 56 |
+
n_embd: int = 128,
|
| 57 |
+
n_layer: int = 6,
|
| 58 |
+
n_head: int = 4,
|
| 59 |
+
n_ctx: int = 256,
|
| 60 |
+
n_inner: Optional[int] = None,
|
| 61 |
+
dropout: float = 0.1,
|
| 62 |
+
layer_norm_epsilon: float = 1e-5,
|
| 63 |
+
tie_weights: bool = True,
|
| 64 |
+
pad_token_id: int = 0,
|
| 65 |
+
bos_token_id: int = 1,
|
| 66 |
+
eos_token_id: int = 2,
|
| 67 |
+
**kwargs,
|
| 68 |
+
):
|
| 69 |
+
super().__init__(
|
| 70 |
+
pad_token_id=pad_token_id,
|
| 71 |
+
bos_token_id=bos_token_id,
|
| 72 |
+
eos_token_id=eos_token_id,
|
| 73 |
+
**kwargs,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
self.vocab_size = vocab_size
|
| 77 |
+
self.n_embd = n_embd
|
| 78 |
+
self.n_layer = n_layer
|
| 79 |
+
self.n_head = n_head
|
| 80 |
+
self.n_ctx = n_ctx
|
| 81 |
+
self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
|
| 82 |
+
self.dropout = dropout
|
| 83 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 84 |
+
self.tie_weights = tie_weights
|
| 85 |
+
# Inform HF base class about tying behavior
|
| 86 |
+
self.tie_word_embeddings = bool(tie_weights)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class MultiHeadAttention(nn.Module):
|
| 90 |
+
"""
|
| 91 |
+
Multi-head self-attention module.
|
| 92 |
+
|
| 93 |
+
This is a standard scaled dot-product attention implementation
|
| 94 |
+
with causal masking for autoregressive generation.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, config: ChessConfig):
|
| 98 |
+
super().__init__()
|
| 99 |
+
|
| 100 |
+
assert config.n_embd % config.n_head == 0, \
|
| 101 |
+
f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
|
| 102 |
+
|
| 103 |
+
self.n_head = config.n_head
|
| 104 |
+
self.n_embd = config.n_embd
|
| 105 |
+
self.head_dim = config.n_embd // config.n_head
|
| 106 |
+
|
| 107 |
+
# Combined QKV projection for efficiency
|
| 108 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 109 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 110 |
+
|
| 111 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 112 |
+
|
| 113 |
+
# Causal mask (will be created on first forward pass)
|
| 114 |
+
self.register_buffer(
|
| 115 |
+
"bias",
|
| 116 |
+
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
|
| 117 |
+
1, 1, config.n_ctx, config.n_ctx
|
| 118 |
+
),
|
| 119 |
+
persistent=False,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def forward(
|
| 123 |
+
self,
|
| 124 |
+
x: torch.Tensor,
|
| 125 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 126 |
+
) -> torch.Tensor:
|
| 127 |
+
batch_size, seq_len, _ = x.size()
|
| 128 |
+
|
| 129 |
+
# Compute Q, K, V
|
| 130 |
+
qkv = self.c_attn(x)
|
| 131 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 132 |
+
|
| 133 |
+
# Reshape for multi-head attention
|
| 134 |
+
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 135 |
+
k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 136 |
+
v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 137 |
+
|
| 138 |
+
# Scaled dot-product attention
|
| 139 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 140 |
+
|
| 141 |
+
# Apply causal mask
|
| 142 |
+
causal_mask = self.bias[:, :, :seq_len, :seq_len]
|
| 143 |
+
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
|
| 144 |
+
|
| 145 |
+
# Apply attention mask (for padding)
|
| 146 |
+
if attention_mask is not None:
|
| 147 |
+
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
|
| 148 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 149 |
+
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
|
| 150 |
+
|
| 151 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 152 |
+
attn_weights = self.dropout(attn_weights)
|
| 153 |
+
|
| 154 |
+
# Apply attention to values
|
| 155 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 156 |
+
|
| 157 |
+
# Reshape back
|
| 158 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(
|
| 159 |
+
batch_size, seq_len, self.n_embd
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Output projection
|
| 163 |
+
attn_output = self.c_proj(attn_output)
|
| 164 |
+
|
| 165 |
+
return attn_output
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class FeedForward(nn.Module):
|
| 169 |
+
"""
|
| 170 |
+
Feed-forward network (MLP) module.
|
| 171 |
+
|
| 172 |
+
Standard two-layer MLP with GELU activation.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(self, config: ChessConfig):
|
| 176 |
+
super().__init__()
|
| 177 |
+
|
| 178 |
+
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
|
| 179 |
+
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
|
| 180 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 181 |
+
|
| 182 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 183 |
+
x = self.c_fc(x)
|
| 184 |
+
x = F.gelu(x)
|
| 185 |
+
x = self.c_proj(x)
|
| 186 |
+
x = self.dropout(x)
|
| 187 |
+
return x
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class TransformerBlock(nn.Module):
|
| 191 |
+
"""
|
| 192 |
+
A single transformer block with attention and feed-forward layers.
|
| 193 |
+
|
| 194 |
+
Uses pre-normalization (LayerNorm before attention/FFN) for better
|
| 195 |
+
training stability.
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
def __init__(self, config: ChessConfig):
|
| 199 |
+
super().__init__()
|
| 200 |
+
|
| 201 |
+
self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 202 |
+
self.attn = MultiHeadAttention(config)
|
| 203 |
+
self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 204 |
+
self.mlp = FeedForward(config)
|
| 205 |
+
|
| 206 |
+
def forward(
|
| 207 |
+
self,
|
| 208 |
+
x: torch.Tensor,
|
| 209 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 210 |
+
) -> torch.Tensor:
|
| 211 |
+
# Pre-norm attention
|
| 212 |
+
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
|
| 213 |
+
# Pre-norm FFN
|
| 214 |
+
x = x + self.mlp(self.ln_2(x))
|
| 215 |
+
return x
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class ChessForCausalLM(PreTrainedModel):
|
| 219 |
+
"""
|
| 220 |
+
Chess Transformer for Causal Language Modeling (next-move prediction).
|
| 221 |
+
|
| 222 |
+
This model is designed to predict the next chess move given a sequence
|
| 223 |
+
of previous moves. It uses a GPT-style architecture with:
|
| 224 |
+
- Token embeddings for chess moves
|
| 225 |
+
- Learned positional embeddings
|
| 226 |
+
- Stacked transformer blocks
|
| 227 |
+
- Linear head for next-token prediction
|
| 228 |
+
|
| 229 |
+
The model supports weight tying between the embedding layer and the
|
| 230 |
+
output projection to save parameters.
|
| 231 |
+
|
| 232 |
+
Example:
|
| 233 |
+
>>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
|
| 234 |
+
>>> model = ChessForCausalLM(config)
|
| 235 |
+
>>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
|
| 236 |
+
>>> outputs = model(**inputs)
|
| 237 |
+
>>> next_move_logits = outputs.logits[:, -1, :]
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
config_class = ChessConfig
|
| 241 |
+
base_model_prefix = "transformer"
|
| 242 |
+
supports_gradient_checkpointing = True
|
| 243 |
+
# Suppress missing-key warning for tied lm_head when loading
|
| 244 |
+
keys_to_ignore_on_load_missing = ["lm_head.weight"]
|
| 245 |
+
|
| 246 |
+
def __init__(self, config: ChessConfig):
|
| 247 |
+
super().__init__(config)
|
| 248 |
+
|
| 249 |
+
# Token and position embeddings
|
| 250 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 251 |
+
self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
|
| 252 |
+
|
| 253 |
+
self.drop = nn.Dropout(config.dropout)
|
| 254 |
+
|
| 255 |
+
# Transformer blocks
|
| 256 |
+
self.h = nn.ModuleList([
|
| 257 |
+
TransformerBlock(config) for _ in range(config.n_layer)
|
| 258 |
+
])
|
| 259 |
+
|
| 260 |
+
# Final layer norm
|
| 261 |
+
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 262 |
+
|
| 263 |
+
# Output head
|
| 264 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 265 |
+
|
| 266 |
+
# Declare tied weights for proper serialization
|
| 267 |
+
if config.tie_weights:
|
| 268 |
+
self._tied_weights_keys = ["lm_head.weight"]
|
| 269 |
+
|
| 270 |
+
# Initialize weights
|
| 271 |
+
self.post_init()
|
| 272 |
+
|
| 273 |
+
# Tie weights if configured
|
| 274 |
+
if config.tie_weights:
|
| 275 |
+
self.tie_weights()
|
| 276 |
+
|
| 277 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 278 |
+
return self.wte
|
| 279 |
+
|
| 280 |
+
def set_input_embeddings(self, new_embeddings: nn.Module):
|
| 281 |
+
self.wte = new_embeddings
|
| 282 |
+
if getattr(self.config, "tie_weights", False):
|
| 283 |
+
self.tie_weights()
|
| 284 |
+
|
| 285 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 286 |
+
return self.lm_head
|
| 287 |
+
|
| 288 |
+
def set_output_embeddings(self, new_embeddings: nn.Module):
|
| 289 |
+
self.lm_head = new_embeddings
|
| 290 |
+
|
| 291 |
+
def tie_weights(self):
|
| 292 |
+
# Use HF helper to tie or clone depending on config
|
| 293 |
+
if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
|
| 294 |
+
self._tie_or_clone_weights(self.lm_head, self.wte)
|
| 295 |
+
|
| 296 |
+
def _init_weights(self, module: nn.Module):
|
| 297 |
+
"""Initialize weights following GPT-2 style."""
|
| 298 |
+
if isinstance(module, nn.Linear):
|
| 299 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 300 |
+
if module.bias is not None:
|
| 301 |
+
torch.nn.init.zeros_(module.bias)
|
| 302 |
+
elif isinstance(module, nn.Embedding):
|
| 303 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 304 |
+
elif isinstance(module, nn.LayerNorm):
|
| 305 |
+
torch.nn.init.ones_(module.weight)
|
| 306 |
+
torch.nn.init.zeros_(module.bias)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
input_ids: torch.LongTensor,
|
| 311 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 312 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 313 |
+
labels: Optional[torch.LongTensor] = None,
|
| 314 |
+
return_dict: Optional[bool] = None,
|
| 315 |
+
**kwargs,
|
| 316 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 317 |
+
"""
|
| 318 |
+
Forward pass of the model.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
input_ids: Token IDs of shape (batch_size, seq_len).
|
| 322 |
+
attention_mask: Attention mask of shape (batch_size, seq_len).
|
| 323 |
+
position_ids: Position IDs of shape (batch_size, seq_len).
|
| 324 |
+
labels: Labels for language modeling loss.
|
| 325 |
+
return_dict: Whether to return a ModelOutput object.
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
CausalLMOutputWithPast containing loss (if labels provided) and logits.
|
| 329 |
+
"""
|
| 330 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 331 |
+
|
| 332 |
+
batch_size, seq_len = input_ids.size()
|
| 333 |
+
device = input_ids.device
|
| 334 |
+
|
| 335 |
+
# Create position IDs if not provided
|
| 336 |
+
if position_ids is None:
|
| 337 |
+
position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
|
| 338 |
+
|
| 339 |
+
# Get embeddings
|
| 340 |
+
token_embeds = self.wte(input_ids)
|
| 341 |
+
position_embeds = self.wpe(position_ids)
|
| 342 |
+
hidden_states = self.drop(token_embeds + position_embeds)
|
| 343 |
+
|
| 344 |
+
# Pass through transformer blocks
|
| 345 |
+
for block in self.h:
|
| 346 |
+
hidden_states = block(hidden_states, attention_mask=attention_mask)
|
| 347 |
+
|
| 348 |
+
# Final layer norm
|
| 349 |
+
hidden_states = self.ln_f(hidden_states)
|
| 350 |
+
|
| 351 |
+
# Get logits
|
| 352 |
+
logits = self.lm_head(hidden_states)
|
| 353 |
+
|
| 354 |
+
# Compute loss if labels are provided
|
| 355 |
+
loss = None
|
| 356 |
+
if labels is not None:
|
| 357 |
+
# Shift logits and labels for next-token prediction
|
| 358 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 359 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 360 |
+
|
| 361 |
+
# Flatten for cross-entropy
|
| 362 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=-100) #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(
|
| 382 |
+
self,
|
| 383 |
+
input_ids: torch.LongTensor,
|
| 384 |
+
temperature: float = 1.0,
|
| 385 |
+
top_k: Optional[int] = None,
|
| 386 |
+
top_p: Optional[float] = None,
|
| 387 |
+
) -> int:
|
| 388 |
+
"""
|
| 389 |
+
Generate the next move given a sequence of moves.
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
input_ids: Token IDs of shape (1, seq_len).
|
| 393 |
+
temperature: Sampling temperature (1.0 = no change).
|
| 394 |
+
top_k: If set, only sample from top k tokens.
|
| 395 |
+
top_p: If set, use nucleus sampling with this threshold.
|
| 396 |
+
|
| 397 |
+
Returns:
|
| 398 |
+
The token ID of the predicted next move.
|
| 399 |
+
"""
|
| 400 |
+
self.eval()
|
| 401 |
+
|
| 402 |
+
# Get logits for the last position
|
| 403 |
+
outputs = self(input_ids)
|
| 404 |
+
logits = outputs.logits[:, -1, :] / temperature
|
| 405 |
+
|
| 406 |
+
# Apply top-k filtering
|
| 407 |
+
if top_k is not None:
|
| 408 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 409 |
+
logits[indices_to_remove] = float("-inf")
|
| 410 |
+
|
| 411 |
+
# Apply top-p (nucleus) filtering
|
| 412 |
+
if top_p is not None:
|
| 413 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 414 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 415 |
+
|
| 416 |
+
# Remove tokens with cumulative probability above the threshold
|
| 417 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 418 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 419 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 420 |
+
|
| 421 |
+
indices_to_remove = sorted_indices_to_remove.scatter(
|
| 422 |
+
dim=-1, index=sorted_indices, src=sorted_indices_to_remove
|
| 423 |
+
)
|
| 424 |
+
logits[indices_to_remove] = float("-inf")
|
| 425 |
+
|
| 426 |
+
# Sample from the distribution
|
| 427 |
+
probs = F.softmax(logits, dim=-1)
|
| 428 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 429 |
+
|
| 430 |
+
return next_token.item()
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
# Register the model with Auto classes for easy loading
|
| 434 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 435 |
+
|
| 436 |
+
AutoConfig.register("chess_transformer", ChessConfig)
|
| 437 |
+
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d969df211c037f308c4b375eace7f2db2fb75587f112966b2bac08b0574c87d
|
| 3 |
+
size 2827568
|
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":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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Decomposed Chess Tokenizer v2 for the Chess Challenge.
|
| 3 |
+
|
| 4 |
+
This tokenizer decomposes moves into structural components:
|
| 5 |
+
- Color (W/B)
|
| 6 |
+
- Piece (P/N/B/R/Q/K)
|
| 7 |
+
- From square (a1-h8)
|
| 8 |
+
- To square (a1-h8)
|
| 9 |
+
- Modifiers (capture, check, checkmate, promotion, castling)
|
| 10 |
+
|
| 11 |
+
This allows the model to learn chess structure and generalize better
|
| 12 |
+
while using a much smaller vocabulary (~90 tokens vs ~1200+).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Dict, List, Optional, Tuple
|
| 22 |
+
|
| 23 |
+
from transformers import PreTrainedTokenizer
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChessTokenizer(PreTrainedTokenizer):
|
| 27 |
+
"""
|
| 28 |
+
Decomposed chess move tokenizer.
|
| 29 |
+
|
| 30 |
+
Breaks moves into structural components for better learning.
|
| 31 |
+
|
| 32 |
+
Example:
|
| 33 |
+
>>> tokenizer = ChessTokenizer()
|
| 34 |
+
>>> tokens = tokenizer.tokenize("WPe2e4 BPe7e5")
|
| 35 |
+
>>> print(tokens)
|
| 36 |
+
['W', 'P', 'e2', 'e4', 'B', 'P', 'e7', 'e5']
|
| 37 |
+
|
| 38 |
+
>>> tokenizer.encode("WNg1f3(+)")
|
| 39 |
+
[1, 5, 8, 39, 29, 12, 2] # [BOS, W, N, g1, f3, +, EOS]
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 43 |
+
vocab_files_names = {"vocab_file": "vocab.json"}
|
| 44 |
+
|
| 45 |
+
# Special tokens
|
| 46 |
+
PAD_TOKEN = "[PAD]"
|
| 47 |
+
BOS_TOKEN = "[BOS]"
|
| 48 |
+
EOS_TOKEN = "[EOS]"
|
| 49 |
+
UNK_TOKEN = "[UNK]"
|
| 50 |
+
SEP_TOKEN = "[SEP]" # Optional: separate moves
|
| 51 |
+
|
| 52 |
+
# Chess components
|
| 53 |
+
# Use [W] and [B] for colors to avoid collision with piece 'B' (Bishop)
|
| 54 |
+
COLORS = ["[W]", "[B]"]
|
| 55 |
+
PIECES = ["P", "N", "B", "R", "Q", "K"]
|
| 56 |
+
FILES = ["a", "b", "c", "d", "e", "f", "g", "h"]
|
| 57 |
+
RANKS = ["1", "2", "3", "4", "5", "6", "7", "8"]
|
| 58 |
+
# Generate all 64 squares
|
| 59 |
+
SQUARES = [f + r for f in FILES for r in ["1", "2", "3", "4", "5", "6", "7", "8"]]
|
| 60 |
+
|
| 61 |
+
# Modifiers
|
| 62 |
+
MODIFIERS = [
|
| 63 |
+
"x", # Capture
|
| 64 |
+
"+", # Check
|
| 65 |
+
"#", # Checkmate (alternative to +*)
|
| 66 |
+
"+*", # Checkmate (dataset format)
|
| 67 |
+
"=Q", # Promotion to Queen
|
| 68 |
+
"=R", # Promotion to Rook
|
| 69 |
+
"=B", # Promotion to Bishop
|
| 70 |
+
"=N", # Promotion to Knight
|
| 71 |
+
"O-O", # Kingside castling (alternative)
|
| 72 |
+
"O-O-O", # Queenside castling (alternative)
|
| 73 |
+
"o", # Kingside castling (dataset format)
|
| 74 |
+
"O", # Queenside castling (dataset format)
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
# Regex pattern to parse extended UCI moves
|
| 78 |
+
# Format: [W|B][Piece][from_sq][to_sq][promotion]?[suffixes]?
|
| 79 |
+
MOVE_PATTERN = re.compile(
|
| 80 |
+
r'^([WB])' # Color
|
| 81 |
+
r'([PNBRQK])' # Piece
|
| 82 |
+
r'([a-h][1-8])' # From square
|
| 83 |
+
r'([a-h][1-8])' # To square
|
| 84 |
+
r'(=[QRBN])?' # Promotion (optional)
|
| 85 |
+
r'(\([xoO+*]+\))?$' # Suffixes in parentheses (optional)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
vocab_file: Optional[str] = None,
|
| 91 |
+
vocab: Optional[Dict[str, int]] = None,
|
| 92 |
+
add_move_separator: bool = False,
|
| 93 |
+
**kwargs,
|
| 94 |
+
):
|
| 95 |
+
"""
|
| 96 |
+
Initialize the decomposed chess tokenizer.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
vocab_file: Path to vocabulary JSON file.
|
| 100 |
+
vocab: Pre-built vocabulary dictionary.
|
| 101 |
+
add_move_separator: Whether to add [SEP] between moves.
|
| 102 |
+
"""
|
| 103 |
+
self._pad_token = self.PAD_TOKEN
|
| 104 |
+
self._bos_token = self.BOS_TOKEN
|
| 105 |
+
self._eos_token = self.EOS_TOKEN
|
| 106 |
+
self._unk_token = self.UNK_TOKEN
|
| 107 |
+
self.add_move_separator = add_move_separator
|
| 108 |
+
|
| 109 |
+
# Remove duplicates from kwargs
|
| 110 |
+
kwargs.pop("pad_token", None)
|
| 111 |
+
kwargs.pop("bos_token", None)
|
| 112 |
+
kwargs.pop("eos_token", None)
|
| 113 |
+
kwargs.pop("unk_token", None)
|
| 114 |
+
|
| 115 |
+
# Load or create vocabulary
|
| 116 |
+
if vocab is not None:
|
| 117 |
+
self._vocab = vocab
|
| 118 |
+
elif vocab_file is not None and os.path.exists(vocab_file):
|
| 119 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 120 |
+
self._vocab = json.load(f)
|
| 121 |
+
else:
|
| 122 |
+
self._vocab = self._create_vocab()
|
| 123 |
+
|
| 124 |
+
# Reverse mapping
|
| 125 |
+
self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
|
| 126 |
+
|
| 127 |
+
super().__init__(
|
| 128 |
+
pad_token=self._pad_token,
|
| 129 |
+
bos_token=self._bos_token,
|
| 130 |
+
eos_token=self._eos_token,
|
| 131 |
+
unk_token=self._unk_token,
|
| 132 |
+
**kwargs,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def _create_vocab(self) -> Dict[str, int]:
|
| 136 |
+
"""Create the fixed vocabulary from chess components."""
|
| 137 |
+
tokens = []
|
| 138 |
+
|
| 139 |
+
# Special tokens first
|
| 140 |
+
tokens.extend([self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN])
|
| 141 |
+
if self.add_move_separator:
|
| 142 |
+
tokens.append(self.SEP_TOKEN)
|
| 143 |
+
|
| 144 |
+
# Colors
|
| 145 |
+
tokens.extend(self.COLORS)
|
| 146 |
+
|
| 147 |
+
# Pieces
|
| 148 |
+
tokens.extend(self.PIECES)
|
| 149 |
+
|
| 150 |
+
# Squares (64)
|
| 151 |
+
tokens.extend(self.SQUARES)
|
| 152 |
+
|
| 153 |
+
# Modifiers
|
| 154 |
+
tokens.extend(self.MODIFIERS)
|
| 155 |
+
|
| 156 |
+
return {token: idx for idx, token in enumerate(tokens)}
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def vocab_size(self) -> int:
|
| 160 |
+
return len(self._vocab)
|
| 161 |
+
|
| 162 |
+
def get_vocab(self) -> Dict[str, int]:
|
| 163 |
+
return dict(self._vocab)
|
| 164 |
+
|
| 165 |
+
def _parse_move(self, move: str) -> List[str]:
|
| 166 |
+
"""
|
| 167 |
+
Parse a single move into component tokens.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
move: Move in extended UCI format (e.g., "WPe2e4", "BNg8f6(x+)")
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
List of component tokens.
|
| 174 |
+
"""
|
| 175 |
+
match = self.MOVE_PATTERN.match(move)
|
| 176 |
+
|
| 177 |
+
if not match:
|
| 178 |
+
# Fallback: return as unknown
|
| 179 |
+
return [self.UNK_TOKEN]
|
| 180 |
+
|
| 181 |
+
tokens = []
|
| 182 |
+
|
| 183 |
+
# Color - map 'W' -> '[W]' and 'B' -> '[B]' to avoid collision with piece Bishop
|
| 184 |
+
color = match.group(1)
|
| 185 |
+
tokens.append(f"[{color}]")
|
| 186 |
+
|
| 187 |
+
# Piece
|
| 188 |
+
tokens.append(match.group(2))
|
| 189 |
+
|
| 190 |
+
# From square
|
| 191 |
+
tokens.append(match.group(3))
|
| 192 |
+
|
| 193 |
+
# To square
|
| 194 |
+
tokens.append(match.group(4))
|
| 195 |
+
|
| 196 |
+
# Promotion (optional)
|
| 197 |
+
if match.group(5):
|
| 198 |
+
tokens.append(match.group(5)) # e.g., "=Q"
|
| 199 |
+
|
| 200 |
+
# Parse suffixes (optional)
|
| 201 |
+
if match.group(6):
|
| 202 |
+
suffix = match.group(6) # e.g., "(x+)"
|
| 203 |
+
# Remove parentheses
|
| 204 |
+
suffix_content = suffix[1:-1]
|
| 205 |
+
|
| 206 |
+
# Parse individual modifiers
|
| 207 |
+
if "x" in suffix_content:
|
| 208 |
+
tokens.append("x")
|
| 209 |
+
if "+*" in suffix_content:
|
| 210 |
+
tokens.append("+*")
|
| 211 |
+
elif "+" in suffix_content:
|
| 212 |
+
tokens.append("+")
|
| 213 |
+
if suffix_content == "o":
|
| 214 |
+
tokens.append("o")
|
| 215 |
+
elif suffix_content == "O":
|
| 216 |
+
tokens.append("O")
|
| 217 |
+
|
| 218 |
+
return tokens
|
| 219 |
+
|
| 220 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 221 |
+
"""
|
| 222 |
+
Tokenize a string of moves.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
text: Space-separated moves in extended UCI format.
|
| 226 |
+
|
| 227 |
+
Returns:
|
| 228 |
+
List of component tokens.
|
| 229 |
+
"""
|
| 230 |
+
tokens = []
|
| 231 |
+
moves = text.strip().split()
|
| 232 |
+
|
| 233 |
+
for i, move in enumerate(moves):
|
| 234 |
+
move_tokens = self._parse_move(move)
|
| 235 |
+
tokens.extend(move_tokens)
|
| 236 |
+
|
| 237 |
+
# Add separator between moves (optional)
|
| 238 |
+
if self.add_move_separator and i < len(moves) - 1:
|
| 239 |
+
tokens.append(self.SEP_TOKEN)
|
| 240 |
+
|
| 241 |
+
return tokens
|
| 242 |
+
|
| 243 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 244 |
+
return self._vocab.get(token, self._vocab.get(self.UNK_TOKEN, 0))
|
| 245 |
+
|
| 246 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 247 |
+
return self._ids_to_tokens.get(index, self.UNK_TOKEN)
|
| 248 |
+
|
| 249 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
| 250 |
+
"""
|
| 251 |
+
Convert tokens back to move string.
|
| 252 |
+
|
| 253 |
+
Reconstructs moves from component tokens.
|
| 254 |
+
"""
|
| 255 |
+
special = {self.PAD_TOKEN, self.BOS_TOKEN, self.EOS_TOKEN, self.UNK_TOKEN, self.SEP_TOKEN}
|
| 256 |
+
|
| 257 |
+
result = []
|
| 258 |
+
current_move = []
|
| 259 |
+
|
| 260 |
+
for token in tokens:
|
| 261 |
+
if token in special:
|
| 262 |
+
if current_move:
|
| 263 |
+
result.append(self._reconstruct_move(current_move))
|
| 264 |
+
current_move = []
|
| 265 |
+
continue
|
| 266 |
+
|
| 267 |
+
current_move.append(token)
|
| 268 |
+
|
| 269 |
+
# Check if we have a complete move
|
| 270 |
+
if self._is_complete_move(current_move):
|
| 271 |
+
result.append(self._reconstruct_move(current_move))
|
| 272 |
+
current_move = []
|
| 273 |
+
|
| 274 |
+
# Handle remaining tokens
|
| 275 |
+
if current_move:
|
| 276 |
+
result.append(self._reconstruct_move(current_move))
|
| 277 |
+
|
| 278 |
+
return " ".join(result)
|
| 279 |
+
|
| 280 |
+
def _is_complete_move(self, tokens: List[str]) -> bool:
|
| 281 |
+
"""Check if tokens form a complete move."""
|
| 282 |
+
if len(tokens) < 4:
|
| 283 |
+
return False
|
| 284 |
+
|
| 285 |
+
# Basic move: Color + Piece + From + To
|
| 286 |
+
if (tokens[0] in self.COLORS and
|
| 287 |
+
tokens[1] in self.PIECES and
|
| 288 |
+
tokens[2] in self.SQUARES and
|
| 289 |
+
tokens[3] in self.SQUARES):
|
| 290 |
+
|
| 291 |
+
# Check if next token would start a new move
|
| 292 |
+
if len(tokens) == 4:
|
| 293 |
+
return True
|
| 294 |
+
|
| 295 |
+
# Check for modifiers
|
| 296 |
+
remaining = tokens[4:]
|
| 297 |
+
for t in remaining:
|
| 298 |
+
if t in self.COLORS:
|
| 299 |
+
return True # Next move starting
|
| 300 |
+
if t not in self.MODIFIERS and not t.startswith("="):
|
| 301 |
+
return True
|
| 302 |
+
|
| 303 |
+
return True
|
| 304 |
+
|
| 305 |
+
return False
|
| 306 |
+
|
| 307 |
+
def _reconstruct_move(self, tokens: List[str]) -> str:
|
| 308 |
+
"""Reconstruct a move string from component tokens."""
|
| 309 |
+
if not tokens:
|
| 310 |
+
return ""
|
| 311 |
+
|
| 312 |
+
# Basic structure: Color + Piece + From + To
|
| 313 |
+
if len(tokens) >= 4:
|
| 314 |
+
# Convert [W] -> W and [B] -> B for colors
|
| 315 |
+
color = tokens[0]
|
| 316 |
+
if color in self.COLORS:
|
| 317 |
+
color = color[1] # Extract 'W' from '[W]' or 'B' from '[B]'
|
| 318 |
+
|
| 319 |
+
move = color + "".join(tokens[1:4])
|
| 320 |
+
|
| 321 |
+
# Add modifiers
|
| 322 |
+
suffixes = []
|
| 323 |
+
for t in tokens[4:]:
|
| 324 |
+
if t.startswith("="):
|
| 325 |
+
move += t
|
| 326 |
+
elif t in ["x", "+", "+*", "o", "O"]:
|
| 327 |
+
suffixes.append(t)
|
| 328 |
+
|
| 329 |
+
if suffixes:
|
| 330 |
+
move += "(" + "".join(suffixes) + ")"
|
| 331 |
+
|
| 332 |
+
return move
|
| 333 |
+
|
| 334 |
+
return "".join(tokens)
|
| 335 |
+
|
| 336 |
+
def save_vocabulary(
|
| 337 |
+
self,
|
| 338 |
+
save_directory: str,
|
| 339 |
+
filename_prefix: Optional[str] = None,
|
| 340 |
+
) -> Tuple[str]:
|
| 341 |
+
if not os.path.isdir(save_directory):
|
| 342 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 343 |
+
|
| 344 |
+
vocab_file = os.path.join(
|
| 345 |
+
save_directory,
|
| 346 |
+
(filename_prefix + "-" if filename_prefix else "") + "vocab.json",
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 350 |
+
json.dump(self._vocab, f, ensure_ascii=False, indent=2)
|
| 351 |
+
|
| 352 |
+
# Also save config with auto_map for HuggingFace to find our custom tokenizer
|
| 353 |
+
# Format: (slow_tokenizer_class, fast_tokenizer_class) - we don't have a fast version
|
| 354 |
+
config = {
|
| 355 |
+
"tokenizer_class": "ChessTokenizer",
|
| 356 |
+
"auto_map": {
|
| 357 |
+
"AutoTokenizer": ["tokenizer.ChessTokenizer", None]
|
| 358 |
+
},
|
| 359 |
+
"add_move_separator": self.add_move_separator,
|
| 360 |
+
"vocab_size": self.vocab_size,
|
| 361 |
+
}
|
| 362 |
+
config_file = os.path.join(save_directory, "tokenizer_config.json")
|
| 363 |
+
with open(config_file, "w", encoding="utf-8") as f:
|
| 364 |
+
json.dump(config, f, indent=2)
|
| 365 |
+
|
| 366 |
+
return (vocab_file,)
|
| 367 |
+
|
| 368 |
+
@classmethod
|
| 369 |
+
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
|
| 370 |
+
"""Load tokenizer from directory or hub."""
|
| 371 |
+
path = Path(pretrained_model_name_or_path)
|
| 372 |
+
|
| 373 |
+
if path.is_dir():
|
| 374 |
+
vocab_file = path / "vocab.json"
|
| 375 |
+
config_file = path / "tokenizer_config.json"
|
| 376 |
+
|
| 377 |
+
add_move_separator = False
|
| 378 |
+
if config_file.exists():
|
| 379 |
+
with open(config_file, "r") as f:
|
| 380 |
+
config = json.load(f)
|
| 381 |
+
add_move_separator = config.get("add_move_separator", False)
|
| 382 |
+
|
| 383 |
+
return cls(
|
| 384 |
+
vocab_file=str(vocab_file) if vocab_file.exists() else None,
|
| 385 |
+
add_move_separator=add_move_separator,
|
| 386 |
+
**kwargs,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
# Fallback to HuggingFace hub
|
| 390 |
+
from huggingface_hub import hf_hub_download
|
| 391 |
+
|
| 392 |
+
vocab_file = hf_hub_download(
|
| 393 |
+
repo_id=pretrained_model_name_or_path,
|
| 394 |
+
filename="vocab.json",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
return cls(vocab_file=vocab_file, **kwargs)
|
| 398 |
+
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "ChessTokenizer",
|
| 3 |
+
"auto_map": {
|
| 4 |
+
"AutoTokenizer": [
|
| 5 |
+
"tokenizer.ChessTokenizer",
|
| 6 |
+
null
|
| 7 |
+
]
|
| 8 |
+
},
|
| 9 |
+
"add_move_separator": false,
|
| 10 |
+
"vocab_size": 88
|
| 11 |
+
}
|
vocab.json
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 29 |
+
"b8": 27,
|
| 30 |
+
"c1": 28,
|
| 31 |
+
"c2": 29,
|
| 32 |
+
"c3": 30,
|
| 33 |
+
"c4": 31,
|
| 34 |
+
"c5": 32,
|
| 35 |
+
"c6": 33,
|
| 36 |
+
"c7": 34,
|
| 37 |
+
"c8": 35,
|
| 38 |
+
"d1": 36,
|
| 39 |
+
"d2": 37,
|
| 40 |
+
"d3": 38,
|
| 41 |
+
"d4": 39,
|
| 42 |
+
"d5": 40,
|
| 43 |
+
"d6": 41,
|
| 44 |
+
"d7": 42,
|
| 45 |
+
"d8": 43,
|
| 46 |
+
"e1": 44,
|
| 47 |
+
"e2": 45,
|
| 48 |
+
"e3": 46,
|
| 49 |
+
"e4": 47,
|
| 50 |
+
"e5": 48,
|
| 51 |
+
"e6": 49,
|
| 52 |
+
"e7": 50,
|
| 53 |
+
"e8": 51,
|
| 54 |
+
"f1": 52,
|
| 55 |
+
"f2": 53,
|
| 56 |
+
"f3": 54,
|
| 57 |
+
"f4": 55,
|
| 58 |
+
"f5": 56,
|
| 59 |
+
"f6": 57,
|
| 60 |
+
"f7": 58,
|
| 61 |
+
"f8": 59,
|
| 62 |
+
"g1": 60,
|
| 63 |
+
"g2": 61,
|
| 64 |
+
"g3": 62,
|
| 65 |
+
"g4": 63,
|
| 66 |
+
"g5": 64,
|
| 67 |
+
"g6": 65,
|
| 68 |
+
"g7": 66,
|
| 69 |
+
"g8": 67,
|
| 70 |
+
"h1": 68,
|
| 71 |
+
"h2": 69,
|
| 72 |
+
"h3": 70,
|
| 73 |
+
"h4": 71,
|
| 74 |
+
"h5": 72,
|
| 75 |
+
"h6": 73,
|
| 76 |
+
"h7": 74,
|
| 77 |
+
"h8": 75,
|
| 78 |
+
"x": 76,
|
| 79 |
+
"+": 77,
|
| 80 |
+
"#": 78,
|
| 81 |
+
"+*": 79,
|
| 82 |
+
"=Q": 80,
|
| 83 |
+
"=R": 81,
|
| 84 |
+
"=B": 82,
|
| 85 |
+
"=N": 83,
|
| 86 |
+
"O-O": 84,
|
| 87 |
+
"O-O-O": 85,
|
| 88 |
+
"o": 86,
|
| 89 |
+
"O": 87
|
| 90 |
+
}
|