File size: 11,817 Bytes
d95f1d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
from torch.nn import functional as F
from torchvision import models
from transformers import PreTrainedModel, PretrainedConfig
from transformers.modeling_outputs import CausalLMOutput
from .configuration_bytegpt import ByteGPTConfig

try:
    from flash_attn.flash_attention import FlashAttention

    FLASH_ATTENTION_AVAILABLE = (
        True and torch.cuda.is_available()
    )  # Only available on CUDA
except ImportError:
    FLASH_ATTENTION_AVAILABLE = False


class Head(nn.Module):
    """One head of self-attention.

    Args:
        head_size (int): The size of the head.
        n_embd (int): The embedding dimension.
        block_size (int): The block size.
        dropout (float): The dropout rate.
        use_flash_attention (bool): Whether to use Flash Attention.

    Attributes:
        key (nn.Linear): The linear layer for computing the keys.
        query (nn.Linear): The linear layer for computing the queries.
        value (nn.Linear): The linear layer for computing the values.
        tril (torch.Tensor): The lower triangular matrix.
        dropout (nn.Dropout): The dropout layer.
        use_flash_attention (bool): Whether to use Flash Attention.
        flash_attention (FlashAttention): The FlashAttention module.
    """

    def __init__(
        self,
        head_size: int,
        n_embd: int,
        block_size: int,
        dropout: float,
        use_flash_attention: bool = False,
    ) -> None:
        super().__init__()
        self.key = nn.Linear(n_embd, head_size, bias=False)
        self.query = nn.Linear(n_embd, head_size, bias=False)
        self.value = nn.Linear(n_embd, head_size, bias=False)
        self.dropout = nn.Dropout(dropout)

        # Only enable flash attention if we're on CUDA
        self.use_flash_attention = use_flash_attention and FLASH_ATTENTION_AVAILABLE
        if self.use_flash_attention:
            print("Using Flash Attention")
            self.flash_attention = FlashAttention()
        else:
            if use_flash_attention:
                print(
                    "Flash Attention requested but not available. Using standard attention."
                )
            self.tril = torch.tril(torch.ones(block_size, block_size))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform forward pass through the attention head.

        Args:
            x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).

        Returns:
            torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
        """
        B, T, C = x.shape
        k = self.key(x)  # (B,T,head_size)
        q = self.query(x)  # (B,T,head_size)
        v = self.value(x)  # (B,T,head_size)

        if self.use_flash_attention:
            # Flash Attention expects shape (B, H, T, D)
            out = self.flash_attention(q.unsqueeze(1), k.unsqueeze(1), v.unsqueeze(1))[
                0
            ].squeeze(1)
        else:
            # Regular attention
            self.tril = self.tril.to(x.device)
            wei = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5  # (B, T, T)
            wei = wei.masked_fill(self.tril[:T, :T] == 0, float("-inf"))  # (B, T, T)
            wei = F.softmax(wei, dim=-1)  # (B, T, T)
            wei = self.dropout(wei)
            out = wei @ v  # (B, T, head_size)

        return out


class MultiHeadAttention(nn.Module):
    """Multiple heads of self-attention in parallel.

    Args:
        num_heads (int): The number of heads.
        head_size (int): The size of each head.
        n_embd (int): The embedding dimension.
        block_size (int): The block size.
        dropout (float): The dropout rate.
        use_flash_attention (bool): Whether to use Flash Attention.

    Attributes:
        heads (nn.Modulelist): The list of attention heads.
        proj (nn.Linear): The linear layer for projecting the concatenated heads.
        dropout (nn.Dropout): The dropout layer.
    """

    def __init__(
        self,
        num_heads: int,
        head_size: int,
        n_embd: int,
        block_size: int,
        dropout: float,
        use_flash_attention: bool = False,
    ) -> None:
        super().__init__()
        self.heads = nn.ModuleList(
            [
                Head(
                    head_size,
                    n_embd,
                    block_size,
                    dropout,
                    use_flash_attention=use_flash_attention,
                )
                for _ in range(num_heads)
            ]
        )
        self.proj = nn.Linear(n_embd, n_embd)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform forward pass through the multi-head attention layer.

        Args:
            x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).

        Returns:
            torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
        """
        out = torch.cat([h(x) for h in self.heads], dim=-1)
        out = self.dropout(self.proj(out))
        return out


class FeedForward(nn.Module):
    """Simple linear layer followed by a non-linearity.

    Args:
        n_embd (int): The embedding dimension.
        dropout (float): The dropout rate.

    Attributes:
        net (nn.Sequential): The sequential network of linear layers and ReLU activation.
    """

    def __init__(self, n_embd: int, dropout: float) -> None:
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.ReLU(),
            nn.Linear(4 * n_embd, n_embd),
            nn.Dropout(dropout),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform forward pass through the feedforward layer.

        Args:
            x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).

        Returns:
            torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
        """
        return self.net(x)


class Block(nn.Module):
    """Transformer block: communication followed by computation.

    Args:
        n_embd (int): The embedding dimension.
        n_head (int): The number of attention heads.
        block_size (int): The block size.
        dropout (float): The dropout rate.
        use_flash_attention (bool): Whether to use Flash Attention.

    Attributes:
        sa (MultiHeadAttention): The multi-head attention layer.
        ffwd (FeedForward): The feedforward layer.
        ln1 (nn.LayerNorm): The layer normalization layer for the first sublayer.
        ln2 (nn.LayerNorm): The layer normalization layer for the second sublayer.
    """

    def __init__(
        self,
        n_embd: int,
        n_head: int,
        block_size: int,
        dropout: float,
        use_flash_attention: bool = False,
    ) -> None:
        super().__init__()
        head_size = n_embd // n_head
        self.sa = MultiHeadAttention(
            n_head,
            head_size,
            n_embd,
            block_size,
            dropout,
            use_flash_attention=use_flash_attention,
        )
        self.ffwd = FeedForward(n_embd, dropout)
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)

        # Remove duplicate flash attention and tril setup since it's handled in Head class
        self.use_flash_attention = use_flash_attention and FLASH_ATTENTION_AVAILABLE
        if self.use_flash_attention:
            print("Using Flash Attention")
        elif use_flash_attention:
            print(
                "Flash Attention requested but not available. Using standard attention."
            )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Perform forward pass through the transformer block.

        Args:
            x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).

        Returns:
            torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
        """
        x = x + self.sa(self.ln1(x))
        x = x + self.ffwd(self.ln2(x))
        return x


class ByteGPTForCausalLM(PreTrainedModel):
    config_class = ByteGPTConfig

    def __init__(
        self,
        config: ByteGPTConfig,
    ):
        super().__init__(config)
        self.block_size = config.block_size
        self.token_embedding_table = nn.Embedding(config.vocab_size, config.n_embd)
        self.position_embedding_table = nn.Embedding(config.block_size, config.n_embd)
        self.blocks = nn.Sequential(
            *[
                Block(
                    config.n_embd,
                    config.n_head,
                    config.block_size,
                    config.dropout,
                    config.use_flash_attention,
                )
                for _ in range(config.n_layer)
            ]
        )
        self.ln_f = nn.LayerNorm(config.n_embd)
        self.lm_head = nn.Linear(config.n_embd, config.vocab_size)

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: torch.Tensor,
        return_dict: bool = True,
        labels: torch.Tensor = None,
        **kwargs
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """
        Forward pass of the model.

        Args:
            idx: Input tensor.
            targets: Target tensor.

        Returns:
            tuple of logits and loss.
        """
        B, T = input_ids.shape

        # Token and position embeddings
        tok_emb = self.token_embedding_table(input_ids)  # (B,T,C)
        pos_emb = self.position_embedding_table(
            torch.arange(T, device=input_ids.device)
        )  # (T,C)
        x = tok_emb + pos_emb  # (B,T,C)

        # Transformer blocks
        x = self.blocks(x)  # (B,T,C)
        x = self.ln_f(x)  # (B,T,C)

        # Language model head
        logits = self.lm_head(x)  # (B,T,vocab_size)

        if labels is None:
            loss = None
        else:
            B, T, C = logits.shape
            logits = logits.view(B * T, C)
            labels = labels.view(B * T)
            loss = F.cross_entropy(logits, labels)

        if not return_dict:
            return (logits, loss)

        return CausalLMOutput(logits=logits, loss=loss)

    def prepare_inputs_for_generation(self, input_ids, **kwargs):
        # Required for .generate() to work
        return {
            "input_ids": input_ids,
            "attention_mask": torch.ones_like(input_ids),
        }

    # def generate(
    #     self, input_ids: torch.Tensor, max_new_tokens: int, temperature: float = 1.0
    # ) -> torch.Tensor:
    #     """
    #     Generate text tokens autoregressively.

    #     Args:
    #         idx: Context tokens
    #         max_new_tokens: Number of tokens to generate
    #         temperature: Sampling temperature (higher = more random)

    #     Returns:
    #         Generated token sequence
    #     """
    #     for _ in range(max_new_tokens):
    #         # Crop context if needed
    #         idx_cond = input_ids[:, -self.block_size :]
    #         # Get predictions
    #         logits, _ = self(idx_cond)
    #         # Focus only on the last time step
    #         logits = logits[:, -1, :] / temperature
    #         # Apply softmax to get probabilities
    #         probs = F.softmax(logits, dim=-1)
    #         # Sample from the distribution
    #         idx_next = torch.multinomial(probs, num_samples=1)
    #         # Append sampled index to the running sequence
    #         idx = torch.cat((idx, idx_next), dim=1)
    #     return idx