File size: 12,510 Bytes
bc80f73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e017c24
 
bc80f73
 
 
 
 
e017c24
 
 
 
bc80f73
e017c24
bc80f73
 
 
 
e017c24
 
 
 
 
 
 
bc80f73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"""
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 = 84,
        n_embd: int = 128,
        n_layer: int = 7,
        n_head: int = 4,
        n_ctx: int = 512,
        n_inner: Optional[int] = 256,
        dropout: float = 0.1,
        layer_norm_epsilon: float = 1e-5,
        tie_weights: bool = True,
        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.layer_norm_epsilon = layer_norm_epsilon
        self.tie_weights = tie_weights
        # Inform HF base class about tying behavior
        self.tie_word_embeddings = bool(tie_weights)


class MultiHeadAttention(nn.Module):
    """
    Multi-head self-attention module.
    
    This is a standard scaled dot-product attention implementation
    with causal masking for autoregressive generation.
    """
    
    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)
    
    def forward(
        self,
        x: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        batch_size, seq_len, _ = x.size()
        
        qkv = self.c_attn(x)
        q, k, v = qkv.split(self.n_embd, dim=2)
        
        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_head, self.head_dim).transpose(1, 2)
        v = v.view(batch_size, seq_len, self.n_head, self.head_dim).transpose(1, 2)
        
        attn_weights = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
        
        causal = torch.ones(seq_len, seq_len, device=x.device, dtype=torch.bool).tril()
        attn_weights = attn_weights.masked_fill(~causal.view(1, 1, seq_len, seq_len), float("-inf"))
        
        if attention_mask is not None:
            attention_mask = attention_mask.to(torch.bool)
            attn_weights = attn_weights.masked_fill(~attention_mask.view(batch_size, 1, 1, seq_len), float("-inf"))
        
        attn_weights = F.softmax(attn_weights, dim=-1)
        attn_weights = self.dropout(attn_weights)
        
        attn_output = torch.matmul(attn_weights, v)
        
        attn_output = attn_output.transpose(1, 2).contiguous().view(
            batch_size, seq_len, self.n_embd
        )
        
        attn_output = self.c_proj(attn_output)
        
        return attn_output


class FeedForward(nn.Module):
    """
    Feed-forward network (MLP) adapted for GLU weights.
    Matches checkpoint: c_fc is double width (640), c_proj is single width (320).
    """
    
    def __init__(self, config: ChessConfig):
        super().__init__()
        
        # Le checkpoint a un biais de 640 ici -> On double n_inner
        self.c_fc = nn.Linear(config.n_embd, config.n_inner * 2)
        
        # Le checkpoint a des poids [96, 320] ici -> On reste à n_inner simple
        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)
        
        # On coupe le tenseur en deux (GLU logic) : 640 -> 320 + 320
        x, gate = x.chunk(2, dim=-1)
        
        # On applique l'activation sur la porte et on multiplie
        x = x * F.gelu(gate) 
        
        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 (LayerNorm before attention/FFN) for better
    training stability.
    """
    
    def __init__(self, config: ChessConfig):
        super().__init__()
        
        self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
        self.attn = MultiHeadAttention(config)
        self.ln_2 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
        self.mlp = FeedForward(config)
    
    def forward(
        self,
        x: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        x = x + self.attn(self.ln_1(x), attention_mask=attention_mask)
        x = x + self.mlp(self.ln_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 a GPT-style architecture with:
    - Token embeddings for chess moves
    - Learned positional embeddings
    - 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.
    
    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)
        
        self.wte = nn.Embedding(config.vocab_size, config.n_embd)
        self.wpe = nn.Embedding(config.n_ctx, config.n_embd)
        
        self.drop = nn.Dropout(config.dropout)
        
        self.h = nn.ModuleList([
            TransformerBlock(config) for _ in range(config.n_layer)
        ])
        
        self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
        
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
        
        if config.tie_weights:
            self._tied_weights_keys = ["lm_head.weight"]
        
        self.post_init()
        
        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 following GPT-2 style."""
        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, nn.LayerNorm):
            torch.nn.init.ones_(module.weight)
            torch.nn.init.zeros_(module.bias)
    
    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: Position IDs of shape (batch_size, seq_len).
            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
        
        batch_size, seq_len = input_ids.size()
        device = input_ids.device
        
        if position_ids is None:
            position_ids = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1)
        
        token_embeds = self.wte(input_ids)
        position_embeds = self.wpe(position_ids)
        hidden_states = self.drop(token_embeds + position_embeds)
        
        for block in self.h:
            hidden_states = block(hidden_states, attention_mask=attention_mask)
        
        hidden_states = self.ln_f(hidden_states)
        
        logits = self.lm_head(hidden_states)
        
        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,
        )


# Register the model with Auto classes for easy loading
from transformers import AutoConfig, AutoModelForCausalLM

AutoConfig.register("chess_transformer", ChessConfig)
AutoModelForCausalLM.register(ChessConfig, ChessForCausalLM)