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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 = 76,
|
| 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 |
+
if "auto_map" not in kwargs:
|
| 70 |
+
kwargs["auto_map"] = {
|
| 71 |
+
"AutoConfig": "model.ChessConfig",
|
| 72 |
+
"AutoModelForCausalLM": "model.ChessForCausalLM"
|
| 73 |
+
}
|
| 74 |
+
super().__init__(
|
| 75 |
+
pad_token_id=pad_token_id,
|
| 76 |
+
bos_token_id=bos_token_id,
|
| 77 |
+
eos_token_id=eos_token_id,
|
| 78 |
+
**kwargs,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
self.vocab_size = vocab_size
|
| 82 |
+
self.n_embd = n_embd
|
| 83 |
+
self.n_layer = n_layer
|
| 84 |
+
self.n_head = n_head
|
| 85 |
+
self.n_ctx = n_ctx
|
| 86 |
+
self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
|
| 87 |
+
self.dropout = dropout
|
| 88 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 89 |
+
self.tie_weights = tie_weights
|
| 90 |
+
# Inform HF base class about tying behavior
|
| 91 |
+
self.tie_word_embeddings = bool(tie_weights)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class MultiHeadAttention(nn.Module):
|
| 95 |
+
"""
|
| 96 |
+
Multi-head self-attention module.
|
| 97 |
+
|
| 98 |
+
This is a standard scaled dot-product attention implementation
|
| 99 |
+
with causal masking for autoregressive generation.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(self, config: ChessConfig):
|
| 103 |
+
super().__init__()
|
| 104 |
+
|
| 105 |
+
assert config.n_embd % config.n_head == 0, \
|
| 106 |
+
f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
|
| 107 |
+
|
| 108 |
+
self.n_head = config.n_head
|
| 109 |
+
self.n_embd = config.n_embd
|
| 110 |
+
self.head_dim = config.n_embd // config.n_head
|
| 111 |
+
|
| 112 |
+
# Combined QKV projection for efficiency
|
| 113 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 114 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 115 |
+
|
| 116 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 117 |
+
|
| 118 |
+
# Causal mask (will be created on first forward pass)
|
| 119 |
+
self.register_buffer(
|
| 120 |
+
"bias",
|
| 121 |
+
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
|
| 122 |
+
1, 1, config.n_ctx, config.n_ctx
|
| 123 |
+
),
|
| 124 |
+
persistent=False,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
def forward(
|
| 128 |
+
self,
|
| 129 |
+
x: torch.Tensor,
|
| 130 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 131 |
+
) -> torch.Tensor:
|
| 132 |
+
batch_size, seq_len, _ = x.size()
|
| 133 |
+
|
| 134 |
+
# Compute Q, K, V
|
| 135 |
+
qkv = self.c_attn(x)
|
| 136 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 137 |
+
|
| 138 |
+
# Reshape for multi-head attention
|
| 139 |
+
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 140 |
+
k = k.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 141 |
+
v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 142 |
+
|
| 143 |
+
# Scaled dot-product attention
|
| 144 |
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 145 |
+
|
| 146 |
+
# Apply causal mask
|
| 147 |
+
causal_mask = self.bias[:, :, :seq_len, :seq_len]
|
| 148 |
+
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
|
| 149 |
+
|
| 150 |
+
# Apply attention mask (for padding)
|
| 151 |
+
if attention_mask is not None:
|
| 152 |
+
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
|
| 153 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 154 |
+
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
|
| 155 |
+
|
| 156 |
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
| 157 |
+
attn_weights = self.dropout(attn_weights)
|
| 158 |
+
|
| 159 |
+
# Apply attention to values
|
| 160 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 161 |
+
|
| 162 |
+
# Reshape back
|
| 163 |
+
attn_output = attn_output.transpose(1, 2).contiguous().view(
|
| 164 |
+
batch_size, seq_len, self.n_embd
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Output projection
|
| 168 |
+
attn_output = self.c_proj(attn_output)
|
| 169 |
+
|
| 170 |
+
return attn_output
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class FeedForward(nn.Module):
|
| 174 |
+
"""
|
| 175 |
+
Feed-forward network (MLP) module.
|
| 176 |
+
|
| 177 |
+
Standard two-layer MLP with GELU activation.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
def __init__(self, config: ChessConfig):
|
| 181 |
+
super().__init__()
|
| 182 |
+
|
| 183 |
+
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
|
| 184 |
+
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
|
| 185 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 186 |
+
|
| 187 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 188 |
+
x = self.c_fc(x)
|
| 189 |
+
x = F.gelu(x)
|
| 190 |
+
x = self.c_proj(x)
|
| 191 |
+
x = self.dropout(x)
|
| 192 |
+
return x
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class TransformerBlock(nn.Module):
|
| 196 |
+
"""
|
| 197 |
+
A single transformer block with attention and feed-forward layers.
|
| 198 |
+
|
| 199 |
+
Uses pre-normalization (LayerNorm before attention/FFN) for better
|
| 200 |
+
training stability.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
def __init__(self, config: ChessConfig):
|
| 204 |
+
super().__init__()
|
| 205 |
+
|
| 206 |
+
self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 207 |
+
self.attn = MultiHeadAttention(config)
|
| 208 |
+
self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 209 |
+
self.mlp = FeedForward(config)
|
| 210 |
+
|
| 211 |
+
def forward(
|
| 212 |
+
self,
|
| 213 |
+
x: torch.Tensor,
|
| 214 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 215 |
+
) -> torch.Tensor:
|
| 216 |
+
# Pre-norm attention
|
| 217 |
+
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
|
| 218 |
+
# Pre-norm FFN
|
| 219 |
+
x = x + self.mlp(self.ln_2(x))
|
| 220 |
+
return x
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class ChessForCausalLM(PreTrainedModel):
|
| 224 |
+
"""
|
| 225 |
+
Chess Transformer for Causal Language Modeling (next-move prediction).
|
| 226 |
+
|
| 227 |
+
This model is designed to predict the next chess move given a sequence
|
| 228 |
+
of previous moves. It uses a GPT-style architecture with:
|
| 229 |
+
- Token embeddings for chess moves
|
| 230 |
+
- Learned positional embeddings
|
| 231 |
+
- Stacked transformer blocks
|
| 232 |
+
- Linear head for next-token prediction
|
| 233 |
+
|
| 234 |
+
The model supports weight tying between the embedding layer and the
|
| 235 |
+
output projection to save parameters.
|
| 236 |
+
|
| 237 |
+
Example:
|
| 238 |
+
>>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
|
| 239 |
+
>>> model = ChessForCausalLM(config)
|
| 240 |
+
>>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
|
| 241 |
+
>>> outputs = model(**inputs)
|
| 242 |
+
>>> next_move_logits = outputs.logits[:, -1, :]
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
config_class = ChessConfig
|
| 246 |
+
base_model_prefix = "transformer"
|
| 247 |
+
supports_gradient_checkpointing = True
|
| 248 |
+
# Suppress missing-key warning for tied lm_head when loading
|
| 249 |
+
keys_to_ignore_on_load_missing = ["lm_head.weight"]
|
| 250 |
+
|
| 251 |
+
def __init__(self, config: ChessConfig):
|
| 252 |
+
super().__init__(config)
|
| 253 |
+
|
| 254 |
+
# Token and position embeddings
|
| 255 |
+
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
|
| 256 |
+
self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
|
| 257 |
+
|
| 258 |
+
self.drop = nn.Dropout(config.dropout)
|
| 259 |
+
|
| 260 |
+
# Transformer blocks
|
| 261 |
+
self.h = nn.ModuleList([
|
| 262 |
+
TransformerBlock(config) for _ in range(config.n_layer)
|
| 263 |
+
])
|
| 264 |
+
|
| 265 |
+
# Final layer norm
|
| 266 |
+
self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
| 267 |
+
|
| 268 |
+
# Output head
|
| 269 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 270 |
+
|
| 271 |
+
# Declare tied weights for proper serialization
|
| 272 |
+
if config.tie_weights:
|
| 273 |
+
self._tied_weights_keys = ["lm_head.weight"]
|
| 274 |
+
|
| 275 |
+
# Initialize weights
|
| 276 |
+
self.post_init()
|
| 277 |
+
|
| 278 |
+
# Tie weights if configured
|
| 279 |
+
if config.tie_weights:
|
| 280 |
+
self.tie_weights()
|
| 281 |
+
|
| 282 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 283 |
+
return self.wte
|
| 284 |
+
|
| 285 |
+
def set_input_embeddings(self, new_embeddings: nn.Module):
|
| 286 |
+
self.wte = new_embeddings
|
| 287 |
+
if getattr(self.config, "tie_weights", False):
|
| 288 |
+
self.tie_weights()
|
| 289 |
+
|
| 290 |
+
def get_output_embeddings(self) -> nn.Module:
|
| 291 |
+
return self.lm_head
|
| 292 |
+
|
| 293 |
+
def set_output_embeddings(self, new_embeddings: nn.Module):
|
| 294 |
+
self.lm_head = new_embeddings
|
| 295 |
+
|
| 296 |
+
def tie_weights(self):
|
| 297 |
+
# Use HF helper to tie or clone depending on config
|
| 298 |
+
if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
|
| 299 |
+
self._tie_or_clone_weights(self.lm_head, self.wte)
|
| 300 |
+
|
| 301 |
+
def _init_weights(self, module: nn.Module):
|
| 302 |
+
"""Initialize weights following GPT-2 style."""
|
| 303 |
+
if isinstance(module, nn.Linear):
|
| 304 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 305 |
+
if module.bias is not None:
|
| 306 |
+
torch.nn.init.zeros_(module.bias)
|
| 307 |
+
elif isinstance(module, nn.Embedding):
|
| 308 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 309 |
+
elif isinstance(module, nn.LayerNorm):
|
| 310 |
+
torch.nn.init.ones_(module.weight)
|
| 311 |
+
torch.nn.init.zeros_(module.bias)
|
| 312 |
+
|
| 313 |
+
def forward(
|
| 314 |
+
self,
|
| 315 |
+
input_ids: torch.LongTensor,
|
| 316 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 317 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 318 |
+
labels: Optional[torch.LongTensor] = None,
|
| 319 |
+
return_dict: Optional[bool] = None,
|
| 320 |
+
**kwargs,
|
| 321 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 322 |
+
"""
|
| 323 |
+
Forward pass of the model.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
input_ids: Token IDs of shape (batch_size, seq_len).
|
| 327 |
+
attention_mask: Attention mask of shape (batch_size, seq_len).
|
| 328 |
+
position_ids: Position IDs of shape (batch_size, seq_len).
|
| 329 |
+
labels: Labels for language modeling loss.
|
| 330 |
+
return_dict: Whether to return a ModelOutput object.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
CausalLMOutputWithPast containing loss (if labels provided) and logits.
|
| 334 |
+
"""
|
| 335 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 336 |
+
|
| 337 |
+
batch_size, seq_len = input_ids.size()
|
| 338 |
+
device = input_ids.device
|
| 339 |
+
|
| 340 |
+
# Create position IDs if not provided
|
| 341 |
+
if position_ids is None:
|
| 342 |
+
position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
|
| 343 |
+
|
| 344 |
+
# Get embeddings
|
| 345 |
+
token_embeds = self.wte(input_ids)
|
| 346 |
+
position_embeds = self.wpe(position_ids)
|
| 347 |
+
hidden_states = self.drop(token_embeds + position_embeds)
|
| 348 |
+
|
| 349 |
+
# Pass through transformer blocks
|
| 350 |
+
for block in self.h:
|
| 351 |
+
hidden_states = block(hidden_states, attention_mask=attention_mask)
|
| 352 |
+
|
| 353 |
+
# Final layer norm
|
| 354 |
+
hidden_states = self.ln_f(hidden_states)
|
| 355 |
+
|
| 356 |
+
# Get logits
|
| 357 |
+
logits = self.lm_head(hidden_states)
|
| 358 |
+
|
| 359 |
+
# Compute loss if labels are provided
|
| 360 |
+
loss = None
|
| 361 |
+
if labels is not None:
|
| 362 |
+
# Shift logits and labels for next-token prediction
|
| 363 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 364 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 365 |
+
|
| 366 |
+
# Flatten for cross-entropy
|
| 367 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
|
| 368 |
+
# loss_fct = nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
|
| 369 |
+
loss = loss_fct(
|
| 370 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 371 |
+
shift_labels.view(-1),
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
if not return_dict:
|
| 375 |
+
output = (logits,)
|
| 376 |
+
return ((loss,) + output) if loss is not None else output
|
| 377 |
+
|
| 378 |
+
return CausalLMOutputWithPast(
|
| 379 |
+
loss=loss,
|
| 380 |
+
logits=logits,
|
| 381 |
+
past_key_values=None,
|
| 382 |
+
hidden_states=None,
|
| 383 |
+
attentions=None,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
@torch.no_grad()
|
| 387 |
+
def generate_move(
|
| 388 |
+
self,
|
| 389 |
+
input_ids: torch.LongTensor,
|
| 390 |
+
temperature: float = 1.0,
|
| 391 |
+
top_k: Optional[int] = None,
|
| 392 |
+
top_p: Optional[float] = None,
|
| 393 |
+
) -> int:
|
| 394 |
+
"""
|
| 395 |
+
Generate the next move given a sequence of moves.
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
input_ids: Token IDs of shape (1, seq_len).
|
| 399 |
+
temperature: Sampling temperature (1.0 = no change).
|
| 400 |
+
top_k: If set, only sample from top k tokens.
|
| 401 |
+
top_p: If set, use nucleus sampling with this threshold.
|
| 402 |
+
|
| 403 |
+
Returns:
|
| 404 |
+
The token ID of the predicted next move.
|
| 405 |
+
"""
|
| 406 |
+
self.eval()
|
| 407 |
+
|
| 408 |
+
# Get logits for the last position
|
| 409 |
+
outputs = self(input_ids)
|
| 410 |
+
logits = outputs.logits[:, -1, :] / temperature
|
| 411 |
+
|
| 412 |
+
# Apply top-k filtering
|
| 413 |
+
if top_k is not None:
|
| 414 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 415 |
+
logits[indices_to_remove] = float("-inf")
|
| 416 |
+
|
| 417 |
+
# Apply top-p (nucleus) filtering
|
| 418 |
+
if top_p is not None:
|
| 419 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 420 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 421 |
+
|
| 422 |
+
# Remove tokens with cumulative probability above the threshold
|
| 423 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 424 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 425 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 426 |
+
|
| 427 |
+
indices_to_remove = sorted_indices_to_remove.scatter(
|
| 428 |
+
dim=-1, index=sorted_indices, src=sorted_indices_to_remove
|
| 429 |
+
)
|
| 430 |
+
logits[indices_to_remove] = float("-inf")
|
| 431 |
+
|
| 432 |
+
# Sample from the distribution
|
| 433 |
+
probs = F.softmax(logits, dim=-1)
|
| 434 |
+
next_token = torch.multinomial(probs, num_samples=1)
|
| 435 |
+
|
| 436 |
+
return next_token.item()
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# Register the model with Auto classes for easy loading
|
| 440 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 441 |
+
|
| 442 |
+
AutoConfig.register("chess_transformer", ChessConfig)
|
| 443 |
+
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)
|