File size: 12,266 Bytes
7f1e014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""GPT-style decoder-only Transformer with Flash Attention.

Built from scratch with PyTorch. Uses F.scaled_dot_product_attention
for automatic Flash Attention kernel selection on RTX 5080.
"""

import math

import torch
import torch.nn as nn
import torch.nn.functional as F

from .config import ModelConfig, TrainingConfig


class CausalSelfAttention(nn.Module):
    """Multi-head causal self-attention with Flash Attention via SDPA.

    Uses a single QKV projection followed by head splitting.
    The `is_causal=True` flag in scaled_dot_product_attention
    routes to the Flash Attention kernel on compatible GPUs,
    avoiding materialization of the N×N attention matrix.
    """

    def __init__(self, config: ModelConfig):
        super().__init__()
        assert config.d_model % config.n_heads == 0
        self.n_heads = config.n_heads
        self.d_head = config.d_head
        self.d_model = config.d_model

        # Single linear for Q, K, V -> split into 3
        self.qkv = nn.Linear(config.d_model, 3 * config.d_model, bias=config.bias)
        # Output projection
        self.proj = nn.Linear(config.d_model, config.d_model, bias=config.bias)

        # Dropout on attention weights (only used during training)
        self.attn_dropout = nn.Dropout(config.dropout)
        self.proj_dropout = nn.Dropout(config.dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, C = x.shape  # batch, seq_len, d_model

        # Compute Q, K, V in one projection and split
        qkv = self.qkv(x)  # (B, T, 3*C)
        q, k, v = qkv.split(self.d_model, dim=-1)  # each (B, T, C)

        # Reshape to multi-head: (B, n_heads, T, d_head)
        q = q.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
        k = k.view(B, T, self.n_heads, self.d_head).transpose(1, 2)
        v = v.view(B, T, self.n_heads, self.d_head).transpose(1, 2)

        # Flash Attention via PyTorch SDPA
        # is_causal=True automatically selects the optimal kernel
        y = F.scaled_dot_product_attention(
            q, k, v,
            attn_mask=None,
            dropout_p=self.attn_dropout.p if self.training else 0.0,
            is_causal=True,
        )  # (B, n_heads, T, d_head)

        # Recombine heads: (B, T, C)
        y = y.transpose(1, 2).contiguous().view(B, T, C)

        # Output projection
        y = self.proj_dropout(self.proj(y))
        return y


class MLP(nn.Module):
    """Feed-forward network with GELU activation and 4x expansion.

    Matches GPT-2's exact architecture:
    fc (d_model -> 4*d_model) -> GELU (tanh approx) -> proj (4*d_model -> d_model)
    """

    def __init__(self, config: ModelConfig):
        super().__init__()
        self.fc = nn.Linear(config.d_model, config.d_ff, bias=config.bias)
        self.proj = nn.Linear(config.d_ff, config.d_model, bias=config.bias)
        self.dropout = nn.Dropout(config.dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # GELU with tanh approximation matches GPT-2
        x = self.fc(x)
        x = F.gelu(x, approximate="tanh")
        x = self.proj(x)
        x = self.dropout(x)
        return x


class TransformerBlock(nn.Module):
    """Pre-LayerNorm Transformer block.

    Layout: LN -> Attention -> residual -> LN -> MLP -> residual

    Pre-LN is the standard in modern GPT variants. It stabilizes
    training by applying normalization before each sublayer.
    """

    def __init__(self, config: ModelConfig):
        super().__init__()
        self.ln1 = nn.LayerNorm(config.d_model, bias=config.bias)
        self.attn = CausalSelfAttention(config)
        self.ln2 = nn.LayerNorm(config.d_model, bias=config.bias)
        self.mlp = MLP(config)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x + self.attn(self.ln1(x))
        x = x + self.mlp(self.ln2(x))
        return x


class GPT(nn.Module):
    """Decoder-only GPT-style language model.

    Architecture:
        token_emb + pos_emb -> dropout -> [TransformerBlock x N] -> LayerNorm -> lm_head

    Weight tying: lm_head shares weights with token_embedding, saving ~38M params
    and acting as a regularizer (Press & Wolf, 2017).
    """

    def __init__(self, config: ModelConfig):
        super().__init__()
        self.config = config

        # Token and position embeddings
        self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
        self.pos_embedding = nn.Parameter(
            torch.zeros(1, config.max_seq_len, config.d_model)
        )
        self.drop = nn.Dropout(config.dropout)

        # Transformer blocks
        self.blocks = nn.ModuleList(
            [TransformerBlock(config) for _ in range(config.n_layers)]
        )

        # Final layer norm
        self.ln_f = nn.LayerNorm(config.d_model, bias=config.bias)

        # Initialize weights
        self.apply(self._init_weights)
        # Special scaled init for the output projection per GPT-2
        for pn, p in self.named_parameters():
            if pn.endswith("proj.weight"):
                torch.nn.init.normal_(
                    p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layers)
                )

        # Count parameters
        n_params = sum(p.numel() for p in self.parameters())
        print(
            f"GPT model initialized: {n_params / 1e6:.1f}M parameters "
            f"({config.n_layers} layers, d_model={config.d_model}, "
            f"{config.n_heads} heads)"
        )

    def _init_weights(self, module: nn.Module):
        """GPT-2 style weight initialization."""
        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)

    def forward(
        self, idx: torch.Tensor, targets: torch.Tensor | None = None
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        """Forward pass.

        Args:
            idx: input token indices, shape (batch, seq_len).
            targets: optional target token indices, shape (batch, seq_len).
                     If provided, computes cross-entropy loss.

        Returns:
            (logits, loss) tuple. loss is None if targets is None.
        """
        B, T = idx.shape
        assert T <= self.config.max_seq_len, (
            f"Sequence length {T} exceeds model max_seq_len {self.config.max_seq_len}"
        )

        # Token embeddings + position embeddings
        tok_emb = self.token_embedding(idx)  # (B, T, d_model)
        pos_emb = self.pos_embedding[:, :T, :]  # (1, T, d_model)
        x = self.drop(tok_emb + pos_emb)

        # Transformer blocks
        for block in self.blocks:
            x = block(x)

        # Final layer norm
        x = self.ln_f(x)

        # Weight-tied lm_head: reuse token_embedding.weight
        logits = F.linear(x, self.token_embedding.weight)  # (B, T, vocab_size)

        loss = None
        if targets is not None:
            # Flatten for cross-entropy: (B*T, vocab_size) vs (B*T,)
            loss = F.cross_entropy(
                logits.view(-1, logits.size(-1)), targets.view(-1)
            )

        return logits, loss

    @torch.no_grad()
    def generate(
        self,
        idx: torch.Tensor,
        max_new_tokens: int,
        temperature: float = 1.0,
        top_k: int | None = None,
    ) -> torch.Tensor:
        """Autoregressive text generation.

        Args:
            idx: starting token indices, shape (1, seq_len).
            max_new_tokens: number of tokens to generate.
            temperature: scales logits before softmax.
                         - 1.0: default sampling
                         - <1.0: sharper, more deterministic
                         - 0.0: greedy (argmax)
            top_k: if set, only sample from the top-k most likely tokens.

        Returns:
            token indices with generated tokens appended, shape (1, seq_len + max_new_tokens).
        """
        self.eval()
        for _ in range(max_new_tokens):
            # Crop context to max_seq_len
            idx_cond = idx[:, -self.config.max_seq_len :]

            # Forward pass
            logits, _ = self(idx_cond)  # (1, T, vocab_size)
            logits = logits[:, -1, :]  # Only the last position

            # Apply temperature
            if temperature == 0.0:
                # Greedy
                idx_next = logits.argmax(dim=-1, keepdim=True)
            else:
                logits = logits / temperature
                # Top-k filtering
                if top_k is not None and top_k > 0:
                    v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
                    logits[logits < v[:, -1:]] = float("-inf")
                # Sample from distribution
                probs = F.softmax(logits, dim=-1)
                idx_next = torch.multinomial(probs, num_samples=1)

            idx = torch.cat([idx, idx_next], dim=-1)

        return idx

    def configure_optimizers(
        self, training_config: TrainingConfig, device: torch.device
    ) -> torch.optim.Optimizer:
        """Create AdamW optimizer with weight-decay / no-weight-decay split.

        Per GPT-2/3 convention:
        - Weight decay applies to all weight tensors from nn.Linear and nn.Embedding.
        - No weight decay on biases and LayerNorm parameters (weight & bias).
        """
        # Separate parameters
        decay_params = []
        no_decay_params = []
        decay_names = []
        no_decay_names = []

        for pn, p in self.named_parameters():
            if not p.requires_grad:
                continue
            # Weight tensors in matmul and embedding layers get weight decay
            if p.dim() >= 2:
                decay_params.append(p)
                decay_names.append(pn)
            else:
                no_decay_params.append(p)
                no_decay_names.append(pn)

        param_groups = [
            {"params": decay_params, "weight_decay": training_config.weight_decay},
            {"params": no_decay_params, "weight_decay": 0.0},
        ]

        # Use the fused AdamW kernel if available (faster)
        fused_available = "fused" in torch.optim.AdamW.__init__.__code__.co_varnames
        optimizer = torch.optim.AdamW(
            param_groups,
            lr=training_config.peak_lr,
            betas=(training_config.beta1, training_config.beta2),
            eps=training_config.epsilon,
            fused=fused_available,
        )

        print(f"Optimizer: AdamW (fused={fused_available})")
        print(
            f"  Weight decay params: {sum(p.numel() for p in decay_params) / 1e6:.1f}M "
            f"({len(decay_params)} tensors)"
        )
        print(
            f"  No weight decay params: {sum(p.numel() for p in no_decay_params) / 1e6:.1f}M "
            f"({len(no_decay_params)} tensors)"
        )

        return optimizer

    def estimate_vram(self, batch_size: int, seq_len: int, dtype_size: int = 2) -> dict:
        """Estimate VRAM usage (rough, for sanity checking).

        Args:
            batch_size: micro batch size.
            seq_len: sequence length.
            dtype_size: bytes per element (2 for bf16, 4 for fp32).

        Returns:
            dict with GiB estimates for weights, optimizer states, activations.
        """
        n_params = sum(p.numel() for p in self.parameters())
        # Weights in bf16
        weights_gib = (n_params * dtype_size) / (1024**3)
        # Optimizer: fp32 master params + 2x AdamW momentum buffers (fp32) = 3 * 4 bytes
        optimizer_gib = (n_params * 12) / (1024**3)
        # Rough activation estimate for SDPA (no N^2 attention matrix)
        # ~ 34 * d_model * batch * seq * layers bytes
        activation_gib = (
            34 * self.config.d_model * batch_size * seq_len * self.config.n_layers
        ) / (1024**3)

        return {
            "weights_bf16": round(weights_gib, 2),
            "optimizer_fp32": round(optimizer_gib, 2),
            "activations_approx": round(activation_gib, 2),
            "total_approx": round(weights_gib + optimizer_gib + activation_gib, 2),
        }