File size: 11,477 Bytes
fd448dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Standard Transformer language model implementation."""

import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F

from taoTrain.core import BaseModel
from taoTrain.config import ModelConfig
from .registry import register_architecture


# ============================================================================
# Components
# ============================================================================


class PositionalEmbedding(nn.Module):
    """Sinusoidal positional embeddings."""
    
    def __init__(self, dim: int, max_seq_length: int = 2048):
        """Initialize positional embeddings."""
        super().__init__()
        self.dim = dim
        self.max_seq_length = max_seq_length
        
        # Precompute positional embeddings
        pe = torch.zeros(max_seq_length, dim)
        pos = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim))
        
        pe[:, 0::2] = torch.sin(pos * div_term)
        if dim % 2 == 1:
            pe[:, 1::2] = torch.cos(pos * div_term[:-1])
        else:
            pe[:, 1::2] = torch.cos(pos * div_term)
        
        self.register_buffer("pe", pe, persistent=False)
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """

        Add positional embeddings to input.

        

        Args:

            x: Input tensor (batch, seq_len, hidden_dim)

        

        Returns:

            Input + positional embeddings

        """
        seq_len = x.shape[1]
        return x + self.pe[:seq_len]


class Attention(nn.Module):
    """Multi-head self-attention using scaled dot-product attention."""
    
    def __init__(self, config: ModelConfig):
        """Initialize attention."""
        super().__init__()
        self.hidden_dim = config.hidden_dim
        self.num_heads = config.num_heads
        self.head_dim = config.head_dim
        
        assert self.hidden_dim % self.num_heads == 0
        
        # Linear projections
        self.q_proj = nn.Linear(self.hidden_dim, self.hidden_dim)
        self.k_proj = nn.Linear(self.hidden_dim, self.hidden_dim)
        self.v_proj = nn.Linear(self.hidden_dim, self.hidden_dim)
        self.out_proj = nn.Linear(self.hidden_dim, self.hidden_dim)
        
        self.dropout_p = config.dropout
    
    def forward(

        self,

        x: torch.Tensor,

        attention_mask: Optional[torch.Tensor] = None,

    ) -> torch.Tensor:
        """

        Forward pass using scaled_dot_product_attention.

        

        Args:

            x: Shape (batch, seq_len, hidden_dim)

            attention_mask: Shape (batch, seq_len)

        

        Returns:

            Output: Shape (batch, seq_len, hidden_dim)

        """
        batch_size, seq_len, _ = x.shape
        
        # Project to Q, K, V
        q = self.q_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
        k = self.k_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
        v = self.v_proj(x).reshape(batch_size, seq_len, self.num_heads, self.head_dim)
        
        # Transpose for attention: (batch, num_heads, seq_len, head_dim)
        q = q.transpose(1, 2)
        k = k.transpose(1, 2)
        v = v.transpose(1, 2)
        
        # NOTE: PyTorch's scaled_dot_product_attention does NOT support both
        # explicit attn_mask AND is_causal=True together.
        # When is_causal=True, PyTorch handles causal masking automatically.
        # Padding positions are handled separately via loss computation (labels=-100).
        # See: https://github.com/pytorch/pytorch/issues/96099
        
        # Compute attention using scaled_dot_product_attention
        # is_causal=True automatically applies causal masking
        # We do NOT pass attn_mask when is_causal=True
        out = F.scaled_dot_product_attention(
            q, k, v,
            attn_mask=None,  # Must be None when is_causal=True
            dropout_p=self.dropout_p if self.training else 0.0,
            is_causal=True,
            scale=None  # Uses default scale of 1/sqrt(head_dim)
        )  # (batch, num_heads, seq_len, head_dim)
        
        # Transpose back and reshape
        out = out.transpose(1, 2).contiguous()  # (batch, seq_len, num_heads, head_dim)
        out = out.reshape(batch_size, seq_len, self.hidden_dim)
        
        # Output projection
        out = self.out_proj(out)
        
        return out


class SwiGLU(nn.Module):
    """Swish Gated Linear Unit activation."""
    
    def __init__(self, in_dim: int, out_dim: int, dropout: float = 0.0):
        """

        Initialize SwiGLU.

        

        Args:

            in_dim: Input dimension

            out_dim: Intermediate/hidden dimension

            dropout: Dropout rate

        """
        super().__init__()
        # Project to 2x the intermediate dimension (for value and gate)
        self.fc1 = nn.Linear(in_dim, 2 * out_dim)
        self.fc2 = nn.Linear(out_dim, in_dim)  # Project back to input dimension
        self.dropout = nn.Dropout(dropout)
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """

        Forward pass with SwiGLU activation.

        

        Args:

            x: Input tensor

        

        Returns:

            Gated activation output (same dimension as input)

        """
        # Project to 2x intermediate dimension
        x = self.fc1(x)
        
        # Split into value and gate
        x, gate = x.chunk(2, dim=-1)
        
        # SwiGLU: value * swish(gate) = value * gate * sigmoid(gate)
        x = x * F.silu(gate)  # SiLU is Swish: x * sigmoid(x)
        
        x = self.dropout(x)
        x = self.fc2(x)  # Project back to input dimension
        
        return x


class FeedForward(nn.Module):
    """Feed-forward network with SwiGLU activation."""
    
    def __init__(self, config: ModelConfig):
        """Initialize FFN with SwiGLU."""
        super().__init__()
        self.swiglu = SwiGLU(
            in_dim=config.hidden_dim,
            out_dim=config.intermediate_dim,
            dropout=config.dropout
        )
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Forward pass with SwiGLU activation."""
        return self.swiglu(x)


class TransformerBlock(nn.Module):
    """Single transformer block with attention and FFN."""
    
    def __init__(self, config: ModelConfig):
        """Initialize transformer block."""
        super().__init__()
        self.norm1 = nn.LayerNorm(config.hidden_dim)
        self.attn = Attention(config)
        self.norm2 = nn.LayerNorm(config.hidden_dim)
        self.ffn = FeedForward(config)
    
    def forward(

        self,

        x: torch.Tensor,

        attention_mask: Optional[torch.Tensor] = None,

    ) -> torch.Tensor:
        """Forward pass with pre-norm residual connections."""
        # Attention with residual
        x = x + self.attn(self.norm1(x), attention_mask=attention_mask)
        
        # FFN with residual
        x = x + self.ffn(self.norm2(x))
        
        return x


# ============================================================================
# Transformer LM
# ============================================================================


@register_architecture("transformer")
class TransformerLM(BaseModel):
    """Standard Transformer language model."""
    
    def __init__(self, config: ModelConfig):
        """Initialize Transformer LM."""
        super().__init__(config)
        
        # Embeddings
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_dim)
        self.pos_embed = PositionalEmbedding(config.hidden_dim, max_seq_length=config.max_seq_length)
        self.dropout = nn.Dropout(config.dropout)
        
        # Transformer blocks
        self.blocks = nn.ModuleList([
            TransformerBlock(config) for _ in range(config.num_layers)
        ])
        
        # Final layer norm
        self.final_norm = nn.LayerNorm(config.hidden_dim)
        
        # Output projection (shared with input embeddings for efficiency)
        self.lm_head = nn.Linear(config.hidden_dim, config.vocab_size, bias=False)
        
        # Weight tying (optional)
        self.lm_head.weight = self.embed_tokens.weight
        
        # Initialize weights
        self._init_weights()
    
    def _init_weights(self):
        """Initialize model weights."""
        for module in self.modules():
            if isinstance(module, nn.Linear):
                nn.init.normal_(module.weight, std=self.config.init_std)
                if module.bias is not None:
                    nn.init.zeros_(module.bias)
            elif isinstance(module, nn.Embedding):
                nn.init.normal_(module.weight, std=self.config.init_std)
    
    def forward(

        self,

        input_ids: Optional[torch.Tensor] = None,

        attention_mask: Optional[torch.Tensor] = None,

        labels: Optional[torch.Tensor] = None,

        inputs_embeds: Optional[torch.Tensor] = None,

        pixel_values: Optional[torch.Tensor] = None,

    ) -> dict[str, torch.Tensor]:
        """

        Forward pass.

        

        Args:

            input_ids: (batch_size, seq_len)

            attention_mask: (batch_size, seq_len)

            labels: (batch_size, seq_len) for loss computation

        

        Returns:

            Dict with 'logits' and optionally 'loss'

        """
        if inputs_embeds is None:
            if input_ids is None:
                raise ValueError("Either input_ids or inputs_embeds must be provided")
            batch_size, seq_len = input_ids.shape
            x = self.embed_tokens(input_ids)
        else:
            batch_size, seq_len, _ = inputs_embeds.shape
            x = inputs_embeds

        # Add positional embeddings
        x = self.pos_embed(x)
        
        x = self.dropout(x)
        
        # Transformer blocks
        for block in self.blocks:
            x = block(x, attention_mask=attention_mask)
        
        # Final normalization
        x = self.final_norm(x)
        
        # LM head
        logits = self.lm_head(x)  # (batch, seq_len, vocab_size)
        
        # Loss computation
        loss = None
        if labels is not None:
            # Flatten for loss computation
            logits_flat = logits.view(-1, logits.size(-1))  # (batch * seq_len, vocab_size)
            labels_flat = labels.view(-1)
            valid_label_mask = labels_flat != -100

            if not torch.any(valid_label_mask):
                raise ValueError(
                    "All labels are masked out (-100), so loss cannot be computed. "
                    "This usually indicates a dataset parsing or masking bug."
                )
            
            # Only compute loss on valid targets (ignore -100 tokens)
            loss = F.cross_entropy(
                logits_flat,
                labels_flat,
                reduction='mean',
                ignore_index=-100
            )
        
        return {
            'logits': logits,
            'loss': loss,
        }