Bichrai's picture
Chess Challenge submission by Bichrai
ead5630 verified
"""
Chess Transformer Model for the Chess Challenge.
This module provides a simple GPT-style transformer architecture
designed to fit within the 1M parameter constraint.
Key components:
- ChessConfig: Configuration class for model hyperparameters
- ChessForCausalLM: The main model class for next-move prediction
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PretrainedConfig, PreTrainedModel
from transformers.modeling_outputs import CausalLMOutputWithPast
class RMSNorm(nn.Module):
"""
Root Mean Square Layer Normalization.
RMSNorm is more efficient than LayerNorm as it:
- Does not subtract mean (re-centering)
- Does not have a bias parameter
- Only has scale parameter (weight)
This saves computation and parameters while maintaining performance.
Paper: https://arxiv.org/abs/1910.07467
"""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x: torch.Tensor) -> torch.Tensor:
output = self._norm(x.float()).type_as(x)
return output * self.weight
class RotaryPositionalEmbedding(nn.Module):
"""
Rotary Position Embedding (RoPE).
RoPE encodes absolute positional information with rotation matrices
and incorporates relative positional information naturally.
Advantages over learned embeddings:
- No additional parameters (saves n_ctx * n_embd parameters)
- Better extrapolation to longer sequences
- Encodes relative positions naturally
Paper: https://arxiv.org/abs/2104.09864
"""
def __init__(self, dim: int, max_seq_len: int = 2048, base: int = 10000):
super().__init__()
self.dim = dim
self.max_seq_len = max_seq_len
self.base = base
# Compute inverse frequencies
inv_freq = 1.0 / (self.base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
# Pre-compute frequencies for max_seq_len
self._set_cos_sin_cache(max_seq_len)
def _set_cos_sin_cache(self, seq_len: int):
self.max_cached_len = seq_len
t = torch.arange(seq_len, device=self.inv_freq.device).type_as(self.inv_freq)
freqs = torch.outer(t, self.inv_freq)
# Different from paper, but uses a different permutation to get same result
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer("cos_cached", emb.cos(), persistent=False)
self.register_buffer("sin_cached", emb.sin(), persistent=False)
def forward(self, x: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:
# x: [batch_size, seq_len, n_head, head_dim]
if seq_len > self.max_cached_len:
self._set_cos_sin_cache(seq_len)
return (
self.cos_cached[:seq_len, ...].to(x.device),
self.sin_cached[:seq_len, ...].to(x.device),
)
def apply_rotary_pos_emb(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Apply rotary position embeddings to query and key tensors.
Args:
q: Query tensor of shape [batch_size, seq_len, n_head, head_dim]
k: Key tensor of shape [batch_size, seq_len, n_head, head_dim]
cos: Cosine values of shape [seq_len, head_dim]
sin: Sine values of shape [seq_len, head_dim]
Returns:
Tuple of rotated (q, k) tensors
"""
# Reshape cos and sin for broadcasting
cos = cos.unsqueeze(0).unsqueeze(2) # [1, seq_len, 1, head_dim]
sin = sin.unsqueeze(0).unsqueeze(2) # [1, seq_len, 1, head_dim]
# Rotate half
def rotate_half(x):
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class ChessConfig(PretrainedConfig):
"""
Configuration class for the Chess Transformer model.
This configuration is designed for a ~1M parameter model.
Optimizations applied:
- RMSNorm instead of LayerNorm (fewer params, same performance)
- RoPE instead of learned positional embeddings (saves n_ctx * n_embd params)
- Weight tying between embeddings and output (saves vocab_size * n_embd params)
Parameter budget breakdown (with default values):
- Token Embeddings: 1200 x 128 = 153,600
- Position Embeddings: 0 (using RoPE - no parameters)
- Transformer Layers: 6 x ~115,000 = ~690,000 (RMSNorm saves params)
- LM Head (with weight tying): 0 (shared with embeddings)
- Total: ~843,000 parameters (157k saved vs LayerNorm + learned pos embeddings)
Attributes:
vocab_size: Size of the vocabulary (number of unique moves).
n_embd: Embedding dimension (d_model).
n_layer: Number of transformer layers.
n_head: Number of attention heads.
n_ctx: Maximum sequence length (context window).
n_inner: Feed-forward inner dimension (default: 3 * n_embd).
dropout: Dropout probability.
rms_norm_eps: Epsilon for RMS normalization.
tie_weights: Whether to tie embedding and output weights.
rope_base: Base for RoPE frequency calculation.
"""
model_type = "chess_transformer"
def __init__(
self,
vocab_size: int = 1200,
n_embd: int = 128,
n_layer: int = 6,
n_head: int = 4,
n_ctx: int = 256,
n_inner: Optional[int] = None,
dropout: float = 0.1,
rms_norm_eps: float = 1e-6,
tie_weights: bool = True,
rope_base: int = 10000,
pad_token_id: int = 0,
bos_token_id: int = 1,
eos_token_id: int = 2,
**kwargs,
):
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
**kwargs,
)
self.vocab_size = vocab_size
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
self.n_ctx = n_ctx
self.n_inner = n_inner if n_inner is not None else 3 * n_embd # Reduced from 4x to 3x
self.dropout = dropout
self.rms_norm_eps = rms_norm_eps
self.tie_weights = tie_weights
self.rope_base = rope_base
# Inform HF base class about tying behavior
self.tie_word_embeddings = bool(tie_weights)
class MultiHeadAttention(nn.Module):
"""
Multi-head self-attention module with RoPE.
This implementation uses:
- Rotary Position Embeddings (RoPE) for position encoding
- Causal masking for autoregressive generation
- Scaled dot-product attention
"""
def __init__(self, config: ChessConfig):
super().__init__()
assert config.n_embd % config.n_head == 0, \
f"n_embd ({config.n_embd}) must be divisible by n_head ({config.n_head})"
self.n_head = config.n_head
self.n_embd = config.n_embd
self.head_dim = config.n_embd // config.n_head
# Combined QKV projection for efficiency
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
# RoPE for positional encoding
self.rotary_emb = RotaryPositionalEmbedding(
dim=self.head_dim,
max_seq_len=config.n_ctx,
base=config.rope_base,
)
# Causal mask
self.register_buffer(
"bias",
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
1, 1, config.n_ctx, config.n_ctx
),
persistent=False,
)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
batch_size, seq_len, _ = x.size()
# Compute Q, K, V
qkv = self.c_attn(x)
q, k, v = qkv.split(self.n_embd, dim=2)
# Reshape for multi-head attention: [batch, seq_len, n_head, head_dim]
q = q.view(batch_size, seq_len, self.n_head, self.head_dim)
k = k.view(batch_size, seq_len, self.n_head, self.head_dim)
v = v.view(batch_size, seq_len, self.n_head, self.head_dim)
# Apply RoPE to Q and K
cos, sin = self.rotary_emb(q, seq_len)
q, k = apply_rotary_pos_emb(q, k, cos, sin)
# Transpose for attention: [batch, n_head, seq_len, head_dim]
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
# Scaled dot-product attention
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
# Apply causal mask
causal_mask = self.bias[:, :, :seq_len, :seq_len]
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
# Apply attention mask (for padding)
if attention_mask is not None:
# attention_mask shape: (batch_size, seq_len) -> (batch_size, 1, 1, seq_len)
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
attn_weights = attn_weights.masked_fill(attention_mask == 0, float("-inf"))
attn_weights = F.softmax(attn_weights, dim=-1)
attn_weights = self.dropout(attn_weights)
# Apply attention to values
attn_output = torch.matmul(attn_weights, v)
# Reshape back
attn_output = attn_output.transpose(1, 2).contiguous().view(
batch_size, seq_len, self.n_embd
)
# Output projection
attn_output = self.c_proj(attn_output)
return attn_output
class FeedForward(nn.Module):
"""
Feed-forward network (MLP) module.
Standard two-layer MLP with GELU activation.
"""
def __init__(self, config: ChessConfig):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, config.n_inner)
self.c_proj = nn.Linear(config.n_inner, config.n_embd)
self.dropout = nn.Dropout(config.dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.c_fc(x)
x = F.gelu(x)
x = self.c_proj(x)
x = self.dropout(x)
return x
class TransformerBlock(nn.Module):
"""
A single transformer block with attention and feed-forward layers.
Uses pre-normalization (RMSNorm before attention/FFN) for better
training stability and parameter efficiency.
"""
def __init__(self, config: ChessConfig):
super().__init__()
self.rms_1 = RMSNorm(config.n_embd, eps=config.rms_norm_eps)
self.attn = MultiHeadAttention(config)
self.rms_2 = RMSNorm(config.n_embd, eps=config.rms_norm_eps)
self.mlp = FeedForward(config)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
# Pre-norm attention
x = x + self.attn(self.rms_1(x), attention_mask=attention_mask)
# Pre-norm FFN
x = x + self.mlp(self.rms_2(x))
return x
class ChessForCausalLM(PreTrainedModel):
"""
Chess Transformer for Causal Language Modeling (next-move prediction).
This model is designed to predict the next chess move given a sequence
of previous moves. It uses an optimized GPT-style architecture with:
- Token embeddings for chess moves
- RoPE (Rotary Position Embeddings) - no learned positional embeddings
- RMSNorm for efficient normalization
- Stacked transformer blocks
- Linear head for next-token prediction
The model supports weight tying between the embedding layer and the
output projection to save parameters.
Optimizations:
- RoPE saves n_ctx * n_embd parameters vs learned embeddings
- RMSNorm saves parameters vs LayerNorm (no bias, no mean centering)
- Weight tying saves vocab_size * n_embd parameters
Example:
>>> config = ChessConfig(vocab_size=1200, n_embd=128, n_layer=6)
>>> model = ChessForCausalLM(config)
>>> inputs = {"input_ids": torch.tensor([[1, 42, 87]])}
>>> outputs = model(**inputs)
>>> next_move_logits = outputs.logits[:, -1, :]
"""
config_class = ChessConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
# Suppress missing-key warning for tied lm_head when loading
keys_to_ignore_on_load_missing = ["lm_head.weight"]
def __init__(self, config: ChessConfig):
super().__init__(config)
# Token embeddings (no positional embeddings - using RoPE instead)
self.wte = nn.Embedding(config.vocab_size, config.n_embd)
self.drop = nn.Dropout(config.dropout)
# Transformer blocks
self.h = nn.ModuleList([
TransformerBlock(config) for _ in range(config.n_layer)
])
# Final RMS norm
self.rms_f = RMSNorm(config.n_embd, eps=config.rms_norm_eps)
# Output head
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
# Declare tied weights for proper serialization
if config.tie_weights:
self._tied_weights_keys = ["lm_head.weight"]
# Initialize weights
self.post_init()
# Tie weights if configured
if config.tie_weights:
self.tie_weights()
def get_input_embeddings(self) -> nn.Module:
return self.wte
def set_input_embeddings(self, new_embeddings: nn.Module):
self.wte = new_embeddings
if getattr(self.config, "tie_weights", False):
self.tie_weights()
def get_output_embeddings(self) -> nn.Module:
return self.lm_head
def set_output_embeddings(self, new_embeddings: nn.Module):
self.lm_head = new_embeddings
def tie_weights(self):
# Use HF helper to tie or clone depending on config
if getattr(self.config, "tie_weights", False) or getattr(self.config, "tie_word_embeddings", False):
self._tie_or_clone_weights(self.lm_head, self.wte)
def _init_weights(self, module: nn.Module):
"""Initialize weights following GPT-2 style with adaptations for RMSNorm."""
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
elif isinstance(module, RMSNorm):
torch.nn.init.ones_(module.weight)
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple, CausalLMOutputWithPast]:
"""
Forward pass of the model.
Args:
input_ids: Token IDs of shape (batch_size, seq_len).
attention_mask: Attention mask of shape (batch_size, seq_len).
position_ids: Not used (kept for compatibility). Position encoding via RoPE.
labels: Labels for language modeling loss.
return_dict: Whether to return a ModelOutput object.
Returns:
CausalLMOutputWithPast containing loss (if labels provided) and logits.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Get token embeddings (no positional embeddings - using RoPE in attention)
hidden_states = self.wte(input_ids)
hidden_states = self.drop(hidden_states)
# Pass through transformer blocks
for block in self.h:
hidden_states = block(hidden_states, attention_mask=attention_mask)
# Final RMS norm
hidden_states = self.rms_f(hidden_states)
# Get logits
logits = self.lm_head(hidden_states)
# Compute loss if labels are provided
loss = None
if labels is not None:
# Shift logits and labels for next-token prediction
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten for cross-entropy
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
loss = loss_fct(
shift_logits.view(-1, shift_logits.size(-1)),
shift_labels.view(-1),
)
if not return_dict:
output = (logits,)
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=None,
hidden_states=None,
attentions=None,
)
@torch.no_grad()
def generate_move(
self,
input_ids: torch.LongTensor,
temperature: float = 1.0,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
) -> int:
"""
Generate the next move given a sequence of moves.
Args:
input_ids: Token IDs of shape (1, seq_len).
temperature: Sampling temperature (1.0 = no change).
top_k: If set, only sample from top k tokens.
top_p: If set, use nucleus sampling with this threshold.
Returns:
The token ID of the predicted next move.
"""
self.eval()
# Get logits for the last position
outputs = self(input_ids)
logits = outputs.logits[:, -1, :] / temperature
# Apply top-k filtering
if top_k is not None:
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = float("-inf")
# Apply top-p (nucleus) filtering
if top_p is not None:
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
# Remove tokens with cumulative probability above the threshold
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices_to_remove.scatter(
dim=-1, index=sorted_indices, src=sorted_indices_to_remove
)
logits[indices_to_remove] = float("-inf")
# Sample from the distribution
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
return next_token.item()
# Register the model with Auto classes for easy loading
from transformers import AutoConfig, AutoModelForCausalLM
AutoConfig.register("chess_transformer", ChessConfig)
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)