Download chess_model.py from fmorgens/NextBoard: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/chess_model.py
- Command line
-
hf download hf://spaces/fmorgens/NextBoard/chess_model.py
-
curl -L -o chess_model.py https://huggingface.co/spaces/fmorgens/NextBoard/resolve/main/chess_model.py
20.6 kB
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import math | |
| class TrainingConfig: | |
| """Model configuration for ChessBERT (minimal version without training params).""" | |
| CONTEXT_SIZE = 1188 | |
| VOCAB_SIZE = 4423 # Simplified tokenizer vocab size | |
| HIDDEN_SIZE = 1024 | |
| NUM_LAYERS = 12 | |
| NUM_HEADS = 16 | |
| FF_DIM = 1024 * 4 # 4096 | |
| NUM_DIFFUSION_STEPS = 64 # Kept for backward compatibility | |
| MASK_TOKEN_ID = 2 # [MASK] token ID in simplified tokenizer | |
| # CDLM Configuration (Corrective Diffusion Language Model) | |
| NOISE_SCHEDULE = "front_loaded" # "cosine", "linear", "sqrt", or "front_loaded" | |
| USE_CONTINUOUS_TIME = True # Use continuous t ∈ [0, 1] instead of discrete | |
| CDLM_CORRUPTION_PROB = 0.0 # Disabled: model needs to learn valid boards first | |
| CDLM_LAMBDA = 0.0 # Disabled: no corruption loss | |
| # Block-causal mode ("every board" training). Off for all older checkpoints, which keep the | |
| # exact old computation. On: the sequence is a row of boards (BLOCK_LEN tokens each); a board | |
| # attends to itself and to earlier boards only, never to [PAD], and every board gets its own | |
| # timestep (clean history boards t=0). In play the last board is the one being generated. | |
| BLOCK_CAUSAL = False | |
| BLOCK_LEN = 66 | |
| PAD_TOKEN_ID = 1 | |
| class NoiseSchedule: | |
| """ | |
| MDLM-style noise schedule with α(t) and its derivative. | |
| α(t) represents the probability of keeping the original token at time t. | |
| t ∈ [0, 1] where t=0 is clean data and t=1 is fully masked. | |
| """ | |
| def __init__(self, schedule_type: str = "cosine"): | |
| self.schedule_type = schedule_type | |
| def alpha(self, t: torch.Tensor) -> torch.Tensor: | |
| """ | |
| α(t): probability of keeping original token at time t. | |
| Returns values in [0, 1] where α(0) ≈ 1 and α(1) ≈ 0. | |
| """ | |
| # Ensure t is a tensor | |
| if not isinstance(t, torch.Tensor): | |
| t = torch.tensor(t, dtype=torch.float32) | |
| if self.schedule_type == "cosine": | |
| # Cosine schedule: smooth transition, commonly used in diffusion | |
| return torch.cos(t * math.pi / 2) ** 2 | |
| elif self.schedule_type == "linear": | |
| return 1.0 - t | |
| elif self.schedule_type == "sqrt": | |
| # Slower initial masking, faster at the end | |
| return 1.0 - torch.sqrt(t) | |
| elif self.schedule_type == "front_loaded": | |
| # α(t) = 1 - t³: unmask copies fast, spend time on the hard squares | |
| # At t=0.5 only 12.5% masked (~8 squares) — model mostly trains on | |
| # the "last few positions" scenario which is the actual move decision | |
| return 1.0 - t ** 3 | |
| else: | |
| raise ValueError(f"Unknown schedule: {self.schedule_type}") | |
| def alpha_derivative(self, t: torch.Tensor) -> torch.Tensor: | |
| """α'(t): derivative of α with respect to t (always negative).""" | |
| if not isinstance(t, torch.Tensor): | |
| t = torch.tensor(t, dtype=torch.float32) | |
| if self.schedule_type == "cosine": | |
| # d/dt [cos²(πt/2)] = -π * cos(πt/2) * sin(πt/2) | |
| return -math.pi * torch.cos(t * math.pi / 2) * torch.sin(t * math.pi / 2) | |
| elif self.schedule_type == "linear": | |
| return torch.ones_like(t) * -1.0 | |
| elif self.schedule_type == "sqrt": | |
| return -0.5 / (torch.sqrt(t) + 1e-8) | |
| elif self.schedule_type == "front_loaded": | |
| # d/dt [1 - t³] = -3t² | |
| return -3.0 * t ** 2 | |
| else: | |
| raise ValueError(f"Unknown schedule: {self.schedule_type}") | |
| def loss_weight(self, t: torch.Tensor) -> torch.Tensor: | |
| """ | |
| MDLM loss weight: |α'(t)| / (1 - α(t)) | |
| This weighting comes from the continuous-time ELBO derivation and | |
| naturally emphasizes different timesteps based on the schedule. | |
| """ | |
| alpha_t = self.alpha(t) | |
| alpha_prime = self.alpha_derivative(t) | |
| # Add small epsilon to avoid division by zero at t=0 | |
| return torch.abs(alpha_prime) / (1.0 - alpha_t + 1e-8) | |
| def mask_probability(self, t: torch.Tensor) -> torch.Tensor: | |
| """Probability of masking a token at time t.""" | |
| return 1.0 - self.alpha(t) | |
| class SinusoidalEmbedding(nn.Module): | |
| """ | |
| Sinusoidal positional embedding for continuous timesteps. | |
| Maps continuous t ∈ [0, 1] to a high-dimensional embedding using | |
| sinusoidal functions at different frequencies. | |
| """ | |
| def __init__(self, dim: int): | |
| super().__init__() | |
| self.dim = dim | |
| def forward(self, t: torch.Tensor) -> torch.Tensor: | |
| """ | |
| Args: | |
| t: Tensor of shape [batch_size] with values in [0, 1] | |
| Returns: | |
| Tensor of shape [batch_size, dim] | |
| """ | |
| device = t.device | |
| half_dim = self.dim // 2 | |
| # Create frequency bands | |
| emb = math.log(10000) / (half_dim - 1) | |
| emb = torch.exp(torch.arange(half_dim, device=device) * -emb) | |
| # Outer product: [batch_size, 1] * [1, half_dim] -> [batch_size, half_dim] | |
| emb = t[:, None] * emb[None, :] | |
| # Concatenate sin and cos | |
| emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) | |
| return emb | |
| class RotaryEmbedding(nn.Module): | |
| """ | |
| Rotary Position Embedding (RoPE). | |
| Encodes relative position as rotations in the complex plane, | |
| so "66 positions back" is a single learnable rotation pattern. | |
| """ | |
| def __init__(self, dim: int, max_seq_len: int = 2048, base: float = 10000.0): | |
| super().__init__() | |
| inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) | |
| self.register_buffer("inv_freq", inv_freq) | |
| # Pre-compute cos/sin for all positions | |
| t = torch.arange(max_seq_len, dtype=torch.float32) | |
| freqs = torch.outer(t, inv_freq) # [seq_len, dim/2] | |
| self.register_buffer("cos_cached", freqs.cos()) # [seq_len, dim/2] | |
| self.register_buffer("sin_cached", freqs.sin()) # [seq_len, dim/2] | |
| def forward(self, seq_len: int, device: torch.device): | |
| return ( | |
| self.cos_cached[:seq_len].to(device), | |
| self.sin_cached[:seq_len].to(device), | |
| ) | |
| def apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: | |
| """ | |
| Apply rotary embeddings to input tensor. | |
| x: [batch, heads, seq_len, head_dim] | |
| cos, sin: [seq_len, head_dim/2] | |
| """ | |
| # Split into pairs for rotation | |
| x1 = x[..., : x.shape[-1] // 2] | |
| x2 = x[..., x.shape[-1] // 2 :] | |
| # Broadcast cos/sin to match x shape | |
| cos = cos[None, None, :, :] # [1, 1, seq_len, dim/2] | |
| sin = sin[None, None, :, :] | |
| # Apply rotation: [x1, x2] -> [x1*cos - x2*sin, x1*sin + x2*cos] | |
| return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) | |
| class RMSNorm(nn.Module): | |
| """Root Mean Square Layer Normalization""" | |
| def __init__(self, size: int, eps: float = 1e-6): | |
| super().__init__() | |
| self.size = size | |
| self.eps = eps | |
| self.scale = nn.Parameter(torch.ones(size)) | |
| def forward(self, x): | |
| norm_x = x.norm(2, dim=-1, keepdim=True) | |
| rms_x = norm_x * self.size ** (-1.0 / 2) | |
| x_normed = x / (rms_x + self.eps) | |
| return self.scale * x_normed | |
| class FlashSelfAttention(nn.Module): | |
| """ | |
| Self-attention with RoPE and PyTorch 2.0+ scaled_dot_product_attention. | |
| Automatically uses FlashAttention-2 when available (Ampere+ GPUs). | |
| """ | |
| def __init__(self, hidden_size: int, num_heads: int, dropout: float = 0.0): | |
| super().__init__() | |
| self.hidden_size = hidden_size | |
| self.num_heads = num_heads | |
| self.head_dim = hidden_size // num_heads | |
| self.dropout = dropout | |
| assert hidden_size % num_heads == 0, "hidden_size must be divisible by num_heads" | |
| # Combined QKV projection for efficiency | |
| self.qkv_proj = nn.Linear(hidden_size, 3 * hidden_size, bias=False) | |
| self.out_proj = nn.Linear(hidden_size, hidden_size, bias=False) | |
| def forward(self, x: torch.Tensor, rope_cos: torch.Tensor = None, rope_sin: torch.Tensor = None, | |
| attn_mask: torch.Tensor = None) -> torch.Tensor: | |
| batch_size, seq_len, _ = x.shape | |
| # Project to Q, K, V | |
| qkv = self.qkv_proj(x) | |
| qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim) | |
| qkv = qkv.permute(2, 0, 3, 1, 4) # [3, B, H, S, D] | |
| q, k, v = qkv[0], qkv[1], qkv[2] | |
| # Apply RoPE to Q and K (not V) | |
| if rope_cos is not None and rope_sin is not None: | |
| q = apply_rotary_emb(q, rope_cos, rope_sin) | |
| k = apply_rotary_emb(k, rope_cos, rope_sin) | |
| # Use PyTorch's SDPA - automatically selects FlashAttention when possible | |
| attn_output = F.scaled_dot_product_attention( | |
| q, k, v, | |
| attn_mask=attn_mask, # None (old models): full bidirectional attention | |
| dropout_p=self.dropout if self.training else 0.0, | |
| is_causal=False, # Bidirectional attention for BERT-style model | |
| ) | |
| # Reshape back | |
| attn_output = attn_output.transpose(1, 2).reshape(batch_size, seq_len, self.hidden_size) | |
| return self.out_proj(attn_output) | |
| class TransformerBlock(nn.Module): | |
| """Transformer Block with AdaLN-Zero timestep conditioning, RoPE, and SwiGLU. | |
| DiT-style: timestep controls scale (γ), shift (β), and gate (α) for each | |
| sub-layer via adaptive layer norm. This gives every layer direct access to | |
| the noise level instead of relying on a single additive input embedding. | |
| """ | |
| def __init__(self, config: TrainingConfig): | |
| super().__init__() | |
| self.attention = FlashSelfAttention( | |
| config.HIDDEN_SIZE, config.NUM_HEADS | |
| ) | |
| self.gate_proj = nn.Linear(config.HIDDEN_SIZE, config.FF_DIM, bias=False) | |
| self.up = nn.Linear(config.HIDDEN_SIZE, config.FF_DIM, bias=False) | |
| self.down = nn.Linear(config.FF_DIM, config.HIDDEN_SIZE, bias=False) | |
| self.norm1 = RMSNorm(config.HIDDEN_SIZE) | |
| self.norm2 = RMSNorm(config.HIDDEN_SIZE) | |
| # AdaLN-Zero with bottleneck: project timestep to 6 modulation parameters | |
| # γ1, β1, α1 (attention), γ2, β2, α2 (FFN) | |
| adaln_bottleneck = config.HIDDEN_SIZE // 4 # 256 for hidden=1024 | |
| self.adaLN_modulation = nn.Sequential( | |
| nn.SiLU(), | |
| nn.Linear(config.HIDDEN_SIZE, adaln_bottleneck, bias=False), | |
| nn.SiLU(), | |
| nn.Linear(adaln_bottleneck, 6 * config.HIDDEN_SIZE), | |
| ) | |
| # Initialize final layer to zero so the block starts as identity | |
| nn.init.zeros_(self.adaLN_modulation[3].weight) | |
| nn.init.zeros_(self.adaLN_modulation[3].bias) | |
| def forward(self, x, rope_cos=None, rope_sin=None, t_emb=None, attn_mask=None): | |
| if t_emb is not None and t_emb.dim() == 3: | |
| return self._forward_per_block(x, rope_cos, rope_sin, t_emb, attn_mask) | |
| if t_emb is not None: | |
| # t_emb: [batch, hidden] -> 6 modulation vectors | |
| mod = self.adaLN_modulation(t_emb) # [batch, 6*hidden] | |
| gamma1, beta1, alpha1, gamma2, beta2, alpha2 = mod.chunk(6, dim=-1) | |
| # Expand for broadcasting: [batch, 1, hidden] | |
| gamma1 = gamma1.unsqueeze(1) | |
| beta1 = beta1.unsqueeze(1) | |
| alpha1 = alpha1.unsqueeze(1) | |
| gamma2 = gamma2.unsqueeze(1) | |
| beta2 = beta2.unsqueeze(1) | |
| alpha2 = alpha2.unsqueeze(1) | |
| else: | |
| gamma1 = beta1 = alpha1 = gamma2 = beta2 = alpha2 = 0 | |
| # Attention with AdaLN | |
| normed_x = self.norm1(x) | |
| normed_x = normed_x * (1 + gamma1) + beta1 | |
| attn_output = self.attention(normed_x, rope_cos, rope_sin) | |
| x = x + alpha1 * attn_output | |
| # FFN with AdaLN | |
| normed_x = self.norm2(x) | |
| normed_x = normed_x * (1 + gamma2) + beta2 | |
| ffn_output = self.down( | |
| F.silu(self.gate_proj(normed_x)) * self.up(normed_x) | |
| ) | |
| x = x + alpha2 * ffn_output | |
| return x | |
| def _forward_per_block(self, x, rope_cos, rope_sin, t_emb, attn_mask): | |
| """Same block, but every board (BLOCK_LEN tokens) has its own timestep. | |
| t_emb: [batch, n_blocks, hidden]. Modulation is broadcast over each board's tokens.""" | |
| b, n, h = x.shape | |
| nb = t_emb.shape[1] | |
| g1, b1, a1, g2, b2, a2 = (m.unsqueeze(2) for m in self.adaLN_modulation(t_emb).chunk(6, dim=-1)) | |
| def per_block(v): | |
| return v.view(b, nb, n // nb, h) | |
| normed_x = (per_block(self.norm1(x)) * (1 + g1) + b1).view(b, n, h) | |
| x = x + (per_block(self.attention(normed_x, rope_cos, rope_sin, attn_mask)) * a1).view(b, n, h) | |
| normed_x = (per_block(self.norm2(x)) * (1 + g2) + b2).view(b, n, h) | |
| ffn_output = self.down(F.silu(self.gate_proj(normed_x)) * self.up(normed_x)) | |
| return x + (per_block(ffn_output) * a2).view(b, n, h) | |
| def block_attention_mask(block_slot: torch.Tensor, block_noisy: torch.Tensor, key_valid: torch.Tensor, | |
| block_len: int) -> torch.Tensor: | |
| """Boolean attention mask [batch, 1, seq, seq] (True = may attend) for a row of boards. | |
| block_slot[i]: the board's place in the game window; block_noisy[i]: True for a board being | |
| denoised (a target), False for a clean history board. A clean board sees clean boards at the same | |
| or an earlier slot; a noisy board sees clean boards at earlier slots and itself. Nobody sees | |
| [PAD] tokens (key_valid False), so the amount of padding never changes a result; every token | |
| may see itself so no row is empty. | |
| """ | |
| sq, sk = block_slot[:, None], block_slot[None, :] | |
| nq, nk = block_noisy[:, None], block_noisy[None, :] | |
| same = torch.eye(len(block_slot), dtype=torch.bool, device=block_slot.device) | |
| rule = (~nq & ~nk & (sk <= sq)) | (nq & ~nk & (sk < sq)) | same | |
| rule = rule.repeat_interleave(block_len, 0).repeat_interleave(block_len, 1) # [seq, seq] | |
| mask = rule[None] & key_valid[:, None, :] | |
| mask |= torch.eye(rule.shape[0], dtype=torch.bool, device=rule.device)[None] | |
| return mask[:, None] | |
| class ChessBERT(nn.Module): | |
| """ | |
| ChessBERT: A masked diffusion language model for chess. | |
| Supports both discrete timesteps (backward compatible) and continuous | |
| timesteps (MDLM-style). Implements SUBS parameterization to prevent | |
| the model from predicting [MASK] tokens. | |
| """ | |
| def __init__(self, config: TrainingConfig): | |
| super().__init__() | |
| self.config = config | |
| self.token_embeddings = nn.Embedding(config.VOCAB_SIZE, config.HIDDEN_SIZE) | |
| # This weight is also the output head. nn.Embedding's default std of 1 gives a | |
| # fresh model logits of std ~sqrt(hidden), i.e. a starting loss of ~58 instead of | |
| # ln(vocab) = 8.4. Loaded checkpoints are unaffected. | |
| nn.init.normal_(self.token_embeddings.weight, std=0.02) | |
| # RoPE for relative position encoding | |
| head_dim = config.HIDDEN_SIZE // config.NUM_HEADS | |
| self.rotary_emb = RotaryEmbedding(head_dim, max_seq_len=config.CONTEXT_SIZE) | |
| # Continuous timestep projection (MDLM-style) | |
| # Maps sinusoidal embedding through MLP for richer representation | |
| self.continuous_timestep_proj = nn.Sequential( | |
| SinusoidalEmbedding(config.HIDDEN_SIZE), | |
| nn.Linear(config.HIDDEN_SIZE, config.HIDDEN_SIZE), | |
| nn.SiLU(), | |
| nn.Linear(config.HIDDEN_SIZE, config.HIDDEN_SIZE), | |
| ) | |
| self.encoder = nn.ModuleList( | |
| [TransformerBlock(config) for _ in range(config.NUM_LAYERS)] | |
| ) | |
| self.final_norm = RMSNorm(config.HIDDEN_SIZE) | |
| self.mlm_head = nn.Linear(config.HIDDEN_SIZE, config.VOCAB_SIZE, bias=False) | |
| # Tie weights between embedding and output head | |
| self.mlm_head.weight = self.token_embeddings.weight | |
| def play_layout(self, x, timestep=None): | |
| """Block-causal layout for a play window: history boards (clean, t=0), then the board | |
| being generated (the last BLOCK_LEN tokens) at `timestep`.""" | |
| bl = self.config.BLOCK_LEN | |
| b, n = x.shape | |
| nb = n // bl | |
| block_t = torch.zeros(b, nb, device=x.device, dtype=torch.float32) | |
| if timestep is not None: | |
| block_t[:, -1] = timestep.to(torch.float32) | |
| slot = torch.arange(nb, device=x.device) | |
| noisy = slot == nb - 1 | |
| mask = block_attention_mask(slot, noisy, x != self.config.PAD_TOKEN_ID, bl) | |
| return block_t, torch.arange(n, device=x.device), mask | |
| def hidden_states(self, x, timestep=None, layout=None): | |
| """Final-layer states before final_norm, [batch, seq, hidden]. | |
| Old models: one timestep per sequence, full attention (the original computation). | |
| BLOCK_CAUSAL models: layout = (block_t [batch, n_blocks], positions [seq], attn_mask), | |
| built by play_layout() when not given (training passes its own two-stream layout). | |
| """ | |
| embeddings = self.token_embeddings(x) | |
| if not getattr(self.config, "BLOCK_CAUSAL", False): | |
| # Compute timestep embedding once, pass to every block via AdaLN | |
| t_emb = None | |
| if timestep is not None: | |
| t_emb = self.continuous_timestep_proj(timestep) # [batch, hidden] | |
| # Get RoPE cos/sin for this sequence length | |
| rope_cos, rope_sin = self.rotary_emb(x.shape[1], x.device) | |
| for block in self.encoder: | |
| embeddings = block(embeddings, rope_cos, rope_sin, t_emb) | |
| return embeddings | |
| block_t, positions, attn_mask = layout if layout is not None else self.play_layout(x, timestep) | |
| b, nb = block_t.shape | |
| t_emb = self.continuous_timestep_proj(block_t.reshape(-1)).view(b, nb, -1) | |
| rope_cos = self.rotary_emb.cos_cached[positions].to(x.device) | |
| rope_sin = self.rotary_emb.sin_cached[positions].to(x.device) | |
| for block in self.encoder: | |
| embeddings = block(embeddings, rope_cos, rope_sin, t_emb, attn_mask) | |
| return embeddings | |
| def forward(self, x, timestep=None, apply_subs=True, last_n=None, layout=None): | |
| """ | |
| Forward pass with optional SUBS parameterization. | |
| Args: | |
| x: Input token IDs [batch_size, seq_len] | |
| timestep: Either discrete (long tensor) or continuous (float tensor) | |
| - Discrete: integers in [0, NUM_DIFFUSION_STEPS) | |
| - Continuous: floats in [0, 1] | |
| apply_subs: If True, apply SUBS parameterization (mask logit → -inf) | |
| last_n: If set, only compute logits for the last `last_n` positions | |
| (e.g. 64 for the board being generated). The transformer | |
| still attends over the whole sequence; this only skips the | |
| output head for positions whose logits aren't needed. | |
| Returns: | |
| logits: [batch_size, seq_len or last_n, vocab_size] | |
| """ | |
| embeddings = self.hidden_states(x, timestep, layout) | |
| if last_n is not None: | |
| embeddings = embeddings[:, -last_n:] | |
| normed_output = self.final_norm(embeddings) | |
| logits = self.mlm_head(normed_output) | |
| # --- SUBS Parameterization --- | |
| # Ensure the model never predicts [MASK] token by setting its logit to -inf | |
| # This is a key component of MDLM that prevents degenerate solutions | |
| if apply_subs: | |
| mask_token_id = getattr(self.config, 'MASK_TOKEN_ID', 5039) | |
| logits[:, :, mask_token_id] = float('-inf') | |
| return logits | |
| def forward_with_copy_through(self, x, timestep=None, apply_subs=True): | |
| """ | |
| Forward pass with SUBS copy-through behavior. | |
| For unmasked positions, the model should deterministically output | |
| the input token. This method returns both logits and a mask indicating | |
| which positions should use copy-through. | |
| Args: | |
| x: Input token IDs [batch_size, seq_len] | |
| timestep: Timestep tensor | |
| apply_subs: Apply SUBS parameterization | |
| Returns: | |
| logits: [batch_size, seq_len, vocab_size] | |
| is_masked: [batch_size, seq_len] boolean tensor | |
| """ | |
| logits = self.forward(x, timestep, apply_subs) | |
| # Identify masked positions | |
| mask_token_id = getattr(self.config, 'MASK_TOKEN_ID', 5039) | |
| is_masked = (x == mask_token_id) | |
| return logits, is_masked | |