Chess-Eya / model.py
eyaa99's picture
Chess Challenge submission by eyaa99
2d23967 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 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 ChessConfig(PretrainedConfig):
"""
Configuration class for the Chess Transformer model.
This configuration is designed for a ~1M parameter model.
Students can adjust these values to explore different architectures.
Parameter budget breakdown (with default values):
- Embeddings (vocab): 1200 x 128 = 153,600
- Position Embeddings: 256 x 128 = 32,768
- Transformer Layers: 6 x ~120,000 = ~720,000
- LM Head (with weight tying): 0 (shared with embeddings)
- Total: ~906,000 parameters
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.
layer_norm_epsilon: Epsilon for layer normalization.
tie_weights: Whether to tie embedding and output weights.
"""
model_type = "chess_transformer"
def __init__(
self,
vocab_size: int = 1200,
n_embd: int = 128,
n_layer: int = 6,
n_head: int = 4,
n_kv_head: Optional[int] = None,
n_ctx: int = 256,
n_inner: Optional[int] = None,
dropout: float = 0.1,
rms_norm_epsilon: float = 1e-6,
tie_weights: bool = True,
use_rope: bool = True,
rope_theta: float = 10000.0,
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_kv_head = n_kv_head if n_kv_head is not None else n_head
self.n_ctx = n_ctx
# SwiGLU typically uses 2/3 * 4 * n_embd, rounded to multiple of 64
self.n_inner = n_inner if n_inner is not None else self._compute_swiglu_dim(n_embd)
self.dropout = dropout
self.rms_norm_epsilon = rms_norm_epsilon
self.tie_weights = tie_weights
self.tie_word_embeddings = bool(tie_weights)
self.use_rope = use_rope
self.rope_theta = rope_theta
# For compatibility with src/utils.py parameter estimation
self.layer_norm_epsilon = rms_norm_epsilon
@staticmethod
def _compute_swiglu_dim(n_embd: int) -> int:
"""Compute SwiGLU hidden dimension (typically 8/3 * n_embd, rounded)."""
# Standard SwiGLU uses ~2.67x multiplier
hidden = int(8 * n_embd / 3)
# Round to multiple of 64 for efficiency (optional)
return ((hidden + 63) // 64) * 64
class RMSNorm(nn.Module):
"""
Root Mean Square Layer Normalization.
Simpler and faster than LayerNorm - no mean centering, no bias.
"""
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
# RMSNorm: x * weight / sqrt(mean(x^2) + eps)
norm = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x * norm * self.weight
class RotaryEmbedding(nn.Module):
"""
Rotary Position Embeddings (RoPE).
Encodes position information directly into attention computation
without learnable parameters.
"""
def __init__(self, dim: int, max_seq_len: int = 512, theta: float = 10000.0):
super().__init__()
self.dim = dim
self.max_seq_len = max_seq_len
self.theta = theta
# Precompute frequencies
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
# Precompute cos/sin cache
self._build_cache(max_seq_len)
def _build_cache(self, seq_len: int):
"""Build cos/sin cache for positions."""
t = torch.arange(seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
freqs = torch.outer(t, self.inv_freq)
# Concatenate to get full dim
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, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
"""Return cos and sin for the given sequence length."""
if seq_len > self.max_seq_len:
self._build_cache(seq_len)
self.max_seq_len = seq_len
return (
self.cos_cached[:seq_len].to(device),
self.sin_cached[:seq_len].to(device),
)
def rotate_half(x: torch.Tensor) -> torch.Tensor:
"""Rotate half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
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."""
# q, k: (batch, n_head, seq_len, head_dim)
# cos, sin: (seq_len, head_dim)
cos = cos.unsqueeze(0).unsqueeze(0) # (1, 1, seq_len, head_dim)
sin = sin.unsqueeze(0).unsqueeze(0)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class MultiHeadAttention(nn.Module):
"""
Multi-head self-attention with RoPE.
Supports Grouped Query Attention (GQA) when n_kv_head < n_head.
"""
def __init__(self, config: ChessConfig):
super().__init__()
assert config.n_embd % config.n_head == 0
self.n_head = config.n_head
self.n_kv_head = config.n_kv_head
self.n_embd = config.n_embd
self.head_dim = config.n_embd // config.n_head
self.n_rep = config.n_head // config.n_kv_head # For GQA
# Separate Q, K, V projections for clarity with GQA
self.q_proj = nn.Linear(config.n_embd, config.n_head * self.head_dim, bias=False)
self.k_proj = nn.Linear(config.n_embd, config.n_kv_head * self.head_dim, bias=False)
self.v_proj = nn.Linear(config.n_embd, config.n_kv_head * self.head_dim, bias=False)
self.o_proj = nn.Linear(config.n_head * self.head_dim, config.n_embd, bias=False)
self.dropout = nn.Dropout(config.dropout)
# RoPE
self.rotary_emb = RotaryEmbedding(
self.head_dim,
max_seq_len=config.n_ctx,
theta=config.rope_theta,
)
# Causal mask
self.register_buffer(
"causal_mask",
torch.tril(torch.ones(config.n_ctx, config.n_ctx)).view(
1, 1, config.n_ctx, config.n_ctx
),
persistent=False,
)
def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
"""Repeat KV heads for GQA."""
if self.n_rep == 1:
return x
batch, n_kv_head, seq_len, head_dim = x.shape
x = x[:, :, None, :, :].expand(batch, n_kv_head, self.n_rep, seq_len, head_dim)
return x.reshape(batch, n_kv_head * self.n_rep, seq_len, head_dim)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
batch_size, seq_len, _ = x.size()
# Project Q, K, V
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
# Reshape for attention
q = q.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
k = k.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
v = v.view(batch_size, seq_len, self.n_kv_head, self.head_dim).transpose(1, 2)
# Apply RoPE
cos, sin = self.rotary_emb(seq_len, x.device)
q, k = apply_rotary_pos_emb(q, k, cos, sin)
# Repeat KV for GQA
k = self._repeat_kv(k)
v = self._repeat_kv(v)
# Scaled dot-product attention
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
# Apply causal mask
causal_mask = self.causal_mask[:, :, :seq_len, :seq_len]
attn_weights = attn_weights.masked_fill(causal_mask == 0, float("-inf"))
# Apply padding mask
if attention_mask is not None:
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 and project output
attn_output = attn_output.transpose(1, 2).contiguous().view(
batch_size, seq_len, self.n_embd
)
attn_output = self.o_proj(attn_output)
return attn_output
class SwiGLU(nn.Module):
"""
SwiGLU Feed-Forward Network.
SwiGLU(x) = (xW1 * SiLU(xW_gate)) @ W2
More expressive than standard FFN with similar parameter count.
"""
def __init__(self, config: ChessConfig):
super().__init__()
hidden_dim = config.n_inner
# Gate and up projections (can be fused for efficiency)
self.gate_proj = nn.Linear(config.n_embd, hidden_dim, bias=False)
self.up_proj = nn.Linear(config.n_embd, hidden_dim, bias=False)
self.down_proj = nn.Linear(hidden_dim, config.n_embd, bias=False)
self.dropout = nn.Dropout(config.dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# SwiGLU: SiLU(gate) * up, then down
gate = F.silu(self.gate_proj(x))
up = self.up_proj(x)
x = gate * up
x = self.down_proj(x)
x = self.dropout(x)
return x
class TransformerBlock(nn.Module):
"""
Transformer block with RMSNorm, RoPE attention, and SwiGLU FFN.
Uses pre-normalization for training stability.
"""
def __init__(self, config: ChessConfig):
super().__init__()
self.ln_1 = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
self.attn = MultiHeadAttention(config)
self.ln_2 = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
self.mlp = SwiGLU(config)
def forward(
self,
x: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
# Pre-norm attention with residual
x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
# Pre-norm FFN with residual
x = x + self.mlp(self.ln_2(x))
return x
class ChessForCausalLM(PreTrainedModel):
"""
Chess Transformer for Causal Language Modeling.
Modern architecture with RoPE, SwiGLU, and RMSNorm.
"""
config_class = ChessConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_tied_weights_keys = ["lm_head.weight"]
keys_to_ignore_on_load_missing = ["lm_head.weight"]
def __init__(self, config: ChessConfig):
super().__init__(config)
# Token embeddings (no position embeddings - using RoPE)
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 RMSNorm
self.ln_f = RMSNorm(config.n_embd, eps=config.rms_norm_epsilon)
# Output head
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
# 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):
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."""
std = 0.02
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
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=std)
elif isinstance(module, RMSNorm):
torch.nn.init.ones_(module.weight)
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple, CausalLMOutputWithPast]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Get token embeddings (no position embeddings - RoPE handles position)
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 norm and head
hidden_states = self.ln_f(hidden_states)
logits = self.lm_head(hidden_states)
# Compute loss if labels provided
loss = None
if labels is not None:
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
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 token."""
self.eval()
outputs = self(input_ids)
logits = outputs.logits[:, -1, :] / temperature
if top_k is not None:
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
logits[indices_to_remove] = float("-inf")
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)
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")
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
return next_token.item()