Upload ByteGPT-small
Browse files- README.md +199 -0
- config.json +19 -0
- configuration_bytegpt.py +30 -0
- generation_config.json +4 -0
- model.safetensors +3 -0
- modeling_bytegpt.py +353 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"ByteGPTForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "configuration_bytegpt.ByteGPTConfig",
|
7 |
+
"AutoModelForCausalLM": "modeling_bytegpt.ByteGPTForCausalLM"
|
8 |
+
},
|
9 |
+
"block_size": 1024,
|
10 |
+
"dropout": 0.1,
|
11 |
+
"model_type": "ijk_byte_gpt",
|
12 |
+
"n_embd": 768,
|
13 |
+
"n_head": 12,
|
14 |
+
"n_layer": 12,
|
15 |
+
"torch_dtype": "float32",
|
16 |
+
"transformers_version": "4.48.2",
|
17 |
+
"use_flash_attention": false,
|
18 |
+
"vocab_size": 256
|
19 |
+
}
|
configuration_bytegpt.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class ByteGPTConfig(PretrainedConfig):
|
5 |
+
model_type = "ijk_byte_gpt"
|
6 |
+
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
vocab_size: int = 259,
|
10 |
+
block_size: int = 128,
|
11 |
+
n_embd: int = 64,
|
12 |
+
n_head: int = 4,
|
13 |
+
n_layer: int = 4,
|
14 |
+
dropout: float = 0.1,
|
15 |
+
use_flash_attention: bool = False,
|
16 |
+
_attn_implementation_autoset: bool = False,
|
17 |
+
**kwargs
|
18 |
+
):
|
19 |
+
super().__init__(**kwargs)
|
20 |
+
self.auto_map = {
|
21 |
+
"AutoConfig": "configuration_bytegpt.ByteGPTConfig",
|
22 |
+
"AutoModelForCausalLM": "modeling_bytegpt.ByteGPTForCausalLM",
|
23 |
+
}
|
24 |
+
self.vocab_size = vocab_size
|
25 |
+
self.block_size = block_size
|
26 |
+
self.n_embd = n_embd
|
27 |
+
self.n_head = n_head
|
28 |
+
self.n_layer = n_layer
|
29 |
+
self.dropout = dropout
|
30 |
+
self.use_flash_attention = use_flash_attention
|
generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.48.2"
|
4 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:158fa9d9c157e9e64ae65a338a78d81868eb98b86ad361531459f555cd3ccedf
|
3 |
+
size 344889712
|
modeling_bytegpt.py
ADDED
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn import functional as F
|
4 |
+
from torchvision import models
|
5 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
6 |
+
from transformers.modeling_outputs import CausalLMOutput
|
7 |
+
from .configuration_bytegpt import ByteGPTConfig
|
8 |
+
|
9 |
+
try:
|
10 |
+
from flash_attn.flash_attention import FlashAttention
|
11 |
+
|
12 |
+
FLASH_ATTENTION_AVAILABLE = (
|
13 |
+
True and torch.cuda.is_available()
|
14 |
+
) # Only available on CUDA
|
15 |
+
except ImportError:
|
16 |
+
FLASH_ATTENTION_AVAILABLE = False
|
17 |
+
|
18 |
+
|
19 |
+
class Head(nn.Module):
|
20 |
+
"""One head of self-attention.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
head_size (int): The size of the head.
|
24 |
+
n_embd (int): The embedding dimension.
|
25 |
+
block_size (int): The block size.
|
26 |
+
dropout (float): The dropout rate.
|
27 |
+
use_flash_attention (bool): Whether to use Flash Attention.
|
28 |
+
|
29 |
+
Attributes:
|
30 |
+
key (nn.Linear): The linear layer for computing the keys.
|
31 |
+
query (nn.Linear): The linear layer for computing the queries.
|
32 |
+
value (nn.Linear): The linear layer for computing the values.
|
33 |
+
tril (torch.Tensor): The lower triangular matrix.
|
34 |
+
dropout (nn.Dropout): The dropout layer.
|
35 |
+
use_flash_attention (bool): Whether to use Flash Attention.
|
36 |
+
flash_attention (FlashAttention): The FlashAttention module.
|
37 |
+
"""
|
38 |
+
|
39 |
+
def __init__(
|
40 |
+
self,
|
41 |
+
head_size: int,
|
42 |
+
n_embd: int,
|
43 |
+
block_size: int,
|
44 |
+
dropout: float,
|
45 |
+
use_flash_attention: bool = False,
|
46 |
+
) -> None:
|
47 |
+
super().__init__()
|
48 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
49 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
50 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
51 |
+
self.dropout = nn.Dropout(dropout)
|
52 |
+
|
53 |
+
# Only enable flash attention if we're on CUDA
|
54 |
+
self.use_flash_attention = use_flash_attention and FLASH_ATTENTION_AVAILABLE
|
55 |
+
if self.use_flash_attention:
|
56 |
+
print("Using Flash Attention")
|
57 |
+
self.flash_attention = FlashAttention()
|
58 |
+
else:
|
59 |
+
if use_flash_attention:
|
60 |
+
print(
|
61 |
+
"Flash Attention requested but not available. Using standard attention."
|
62 |
+
)
|
63 |
+
self.tril = torch.tril(torch.ones(block_size, block_size))
|
64 |
+
|
65 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
66 |
+
"""Perform forward pass through the attention head.
|
67 |
+
|
68 |
+
Args:
|
69 |
+
x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).
|
70 |
+
|
71 |
+
Returns:
|
72 |
+
torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
|
73 |
+
"""
|
74 |
+
B, T, C = x.shape
|
75 |
+
k = self.key(x) # (B,T,head_size)
|
76 |
+
q = self.query(x) # (B,T,head_size)
|
77 |
+
v = self.value(x) # (B,T,head_size)
|
78 |
+
|
79 |
+
if self.use_flash_attention:
|
80 |
+
# Flash Attention expects shape (B, H, T, D)
|
81 |
+
out = self.flash_attention(q.unsqueeze(1), k.unsqueeze(1), v.unsqueeze(1))[
|
82 |
+
0
|
83 |
+
].squeeze(1)
|
84 |
+
else:
|
85 |
+
# Regular attention
|
86 |
+
self.tril = self.tril.to(x.device)
|
87 |
+
wei = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5 # (B, T, T)
|
88 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float("-inf")) # (B, T, T)
|
89 |
+
wei = F.softmax(wei, dim=-1) # (B, T, T)
|
90 |
+
wei = self.dropout(wei)
|
91 |
+
out = wei @ v # (B, T, head_size)
|
92 |
+
|
93 |
+
return out
|
94 |
+
|
95 |
+
|
96 |
+
class MultiHeadAttention(nn.Module):
|
97 |
+
"""Multiple heads of self-attention in parallel.
|
98 |
+
|
99 |
+
Args:
|
100 |
+
num_heads (int): The number of heads.
|
101 |
+
head_size (int): The size of each head.
|
102 |
+
n_embd (int): The embedding dimension.
|
103 |
+
block_size (int): The block size.
|
104 |
+
dropout (float): The dropout rate.
|
105 |
+
use_flash_attention (bool): Whether to use Flash Attention.
|
106 |
+
|
107 |
+
Attributes:
|
108 |
+
heads (nn.Modulelist): The list of attention heads.
|
109 |
+
proj (nn.Linear): The linear layer for projecting the concatenated heads.
|
110 |
+
dropout (nn.Dropout): The dropout layer.
|
111 |
+
"""
|
112 |
+
|
113 |
+
def __init__(
|
114 |
+
self,
|
115 |
+
num_heads: int,
|
116 |
+
head_size: int,
|
117 |
+
n_embd: int,
|
118 |
+
block_size: int,
|
119 |
+
dropout: float,
|
120 |
+
use_flash_attention: bool = False,
|
121 |
+
) -> None:
|
122 |
+
super().__init__()
|
123 |
+
self.heads = nn.ModuleList(
|
124 |
+
[
|
125 |
+
Head(
|
126 |
+
head_size,
|
127 |
+
n_embd,
|
128 |
+
block_size,
|
129 |
+
dropout,
|
130 |
+
use_flash_attention=use_flash_attention,
|
131 |
+
)
|
132 |
+
for _ in range(num_heads)
|
133 |
+
]
|
134 |
+
)
|
135 |
+
self.proj = nn.Linear(n_embd, n_embd)
|
136 |
+
self.dropout = nn.Dropout(dropout)
|
137 |
+
|
138 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
139 |
+
"""Perform forward pass through the multi-head attention layer.
|
140 |
+
|
141 |
+
Args:
|
142 |
+
x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).
|
143 |
+
|
144 |
+
Returns:
|
145 |
+
torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
|
146 |
+
"""
|
147 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
148 |
+
out = self.dropout(self.proj(out))
|
149 |
+
return out
|
150 |
+
|
151 |
+
|
152 |
+
class FeedForward(nn.Module):
|
153 |
+
"""Simple linear layer followed by a non-linearity.
|
154 |
+
|
155 |
+
Args:
|
156 |
+
n_embd (int): The embedding dimension.
|
157 |
+
dropout (float): The dropout rate.
|
158 |
+
|
159 |
+
Attributes:
|
160 |
+
net (nn.Sequential): The sequential network of linear layers and ReLU activation.
|
161 |
+
"""
|
162 |
+
|
163 |
+
def __init__(self, n_embd: int, dropout: float) -> None:
|
164 |
+
super().__init__()
|
165 |
+
self.net = nn.Sequential(
|
166 |
+
nn.Linear(n_embd, 4 * n_embd),
|
167 |
+
nn.ReLU(),
|
168 |
+
nn.Linear(4 * n_embd, n_embd),
|
169 |
+
nn.Dropout(dropout),
|
170 |
+
)
|
171 |
+
|
172 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
173 |
+
"""Perform forward pass through the feedforward layer.
|
174 |
+
|
175 |
+
Args:
|
176 |
+
x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).
|
177 |
+
|
178 |
+
Returns:
|
179 |
+
torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
|
180 |
+
"""
|
181 |
+
return self.net(x)
|
182 |
+
|
183 |
+
|
184 |
+
class Block(nn.Module):
|
185 |
+
"""Transformer block: communication followed by computation.
|
186 |
+
|
187 |
+
Args:
|
188 |
+
n_embd (int): The embedding dimension.
|
189 |
+
n_head (int): The number of attention heads.
|
190 |
+
block_size (int): The block size.
|
191 |
+
dropout (float): The dropout rate.
|
192 |
+
use_flash_attention (bool): Whether to use Flash Attention.
|
193 |
+
|
194 |
+
Attributes:
|
195 |
+
sa (MultiHeadAttention): The multi-head attention layer.
|
196 |
+
ffwd (FeedForward): The feedforward layer.
|
197 |
+
ln1 (nn.LayerNorm): The layer normalization layer for the first sublayer.
|
198 |
+
ln2 (nn.LayerNorm): The layer normalization layer for the second sublayer.
|
199 |
+
"""
|
200 |
+
|
201 |
+
def __init__(
|
202 |
+
self,
|
203 |
+
n_embd: int,
|
204 |
+
n_head: int,
|
205 |
+
block_size: int,
|
206 |
+
dropout: float,
|
207 |
+
use_flash_attention: bool = False,
|
208 |
+
) -> None:
|
209 |
+
super().__init__()
|
210 |
+
head_size = n_embd // n_head
|
211 |
+
self.sa = MultiHeadAttention(
|
212 |
+
n_head,
|
213 |
+
head_size,
|
214 |
+
n_embd,
|
215 |
+
block_size,
|
216 |
+
dropout,
|
217 |
+
use_flash_attention=use_flash_attention,
|
218 |
+
)
|
219 |
+
self.ffwd = FeedForward(n_embd, dropout)
|
220 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
221 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
222 |
+
|
223 |
+
# Remove duplicate flash attention and tril setup since it's handled in Head class
|
224 |
+
self.use_flash_attention = use_flash_attention and FLASH_ATTENTION_AVAILABLE
|
225 |
+
if self.use_flash_attention:
|
226 |
+
print("Using Flash Attention")
|
227 |
+
elif use_flash_attention:
|
228 |
+
print(
|
229 |
+
"Flash Attention requested but not available. Using standard attention."
|
230 |
+
)
|
231 |
+
|
232 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
233 |
+
"""Perform forward pass through the transformer block.
|
234 |
+
|
235 |
+
Args:
|
236 |
+
x (torch.Tensor): The input tensor of shape (batch_size, sequence_length, embedding_dimension).
|
237 |
+
|
238 |
+
Returns:
|
239 |
+
torch.Tensor: The output tensor of shape (batch_size, sequence_length, embedding_dimension).
|
240 |
+
"""
|
241 |
+
x = x + self.sa(self.ln1(x))
|
242 |
+
x = x + self.ffwd(self.ln2(x))
|
243 |
+
return x
|
244 |
+
|
245 |
+
|
246 |
+
class ByteGPTForCausalLM(PreTrainedModel):
|
247 |
+
config_class = ByteGPTConfig
|
248 |
+
|
249 |
+
def __init__(
|
250 |
+
self,
|
251 |
+
config: ByteGPTConfig,
|
252 |
+
):
|
253 |
+
super().__init__(config)
|
254 |
+
self.block_size = config.block_size
|
255 |
+
self.token_embedding_table = nn.Embedding(config.vocab_size, config.n_embd)
|
256 |
+
self.position_embedding_table = nn.Embedding(config.block_size, config.n_embd)
|
257 |
+
self.blocks = nn.Sequential(
|
258 |
+
*[
|
259 |
+
Block(
|
260 |
+
config.n_embd,
|
261 |
+
config.n_head,
|
262 |
+
config.block_size,
|
263 |
+
config.dropout,
|
264 |
+
config.use_flash_attention,
|
265 |
+
)
|
266 |
+
for _ in range(config.n_layer)
|
267 |
+
]
|
268 |
+
)
|
269 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
270 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
|
271 |
+
|
272 |
+
def forward(
|
273 |
+
self,
|
274 |
+
input_ids: torch.Tensor,
|
275 |
+
attention_mask: torch.Tensor,
|
276 |
+
return_dict: bool = True,
|
277 |
+
labels: torch.Tensor = None,
|
278 |
+
**kwargs
|
279 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
280 |
+
"""
|
281 |
+
Forward pass of the model.
|
282 |
+
|
283 |
+
Args:
|
284 |
+
idx: Input tensor.
|
285 |
+
targets: Target tensor.
|
286 |
+
|
287 |
+
Returns:
|
288 |
+
tuple of logits and loss.
|
289 |
+
"""
|
290 |
+
B, T = input_ids.shape
|
291 |
+
|
292 |
+
# Token and position embeddings
|
293 |
+
tok_emb = self.token_embedding_table(input_ids) # (B,T,C)
|
294 |
+
pos_emb = self.position_embedding_table(
|
295 |
+
torch.arange(T, device=input_ids.device)
|
296 |
+
) # (T,C)
|
297 |
+
x = tok_emb + pos_emb # (B,T,C)
|
298 |
+
|
299 |
+
# Transformer blocks
|
300 |
+
x = self.blocks(x) # (B,T,C)
|
301 |
+
x = self.ln_f(x) # (B,T,C)
|
302 |
+
|
303 |
+
# Language model head
|
304 |
+
logits = self.lm_head(x) # (B,T,vocab_size)
|
305 |
+
|
306 |
+
if labels is None:
|
307 |
+
loss = None
|
308 |
+
else:
|
309 |
+
B, T, C = logits.shape
|
310 |
+
logits = logits.view(B * T, C)
|
311 |
+
labels = labels.view(B * T)
|
312 |
+
loss = F.cross_entropy(logits, labels)
|
313 |
+
|
314 |
+
if not return_dict:
|
315 |
+
return (logits, loss)
|
316 |
+
|
317 |
+
return CausalLMOutput(logits=logits, loss=loss)
|
318 |
+
|
319 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
320 |
+
# Required for .generate() to work
|
321 |
+
return {
|
322 |
+
"input_ids": input_ids,
|
323 |
+
"attention_mask": torch.ones_like(input_ids),
|
324 |
+
}
|
325 |
+
|
326 |
+
# def generate(
|
327 |
+
# self, input_ids: torch.Tensor, max_new_tokens: int, temperature: float = 1.0
|
328 |
+
# ) -> torch.Tensor:
|
329 |
+
# """
|
330 |
+
# Generate text tokens autoregressively.
|
331 |
+
|
332 |
+
# Args:
|
333 |
+
# idx: Context tokens
|
334 |
+
# max_new_tokens: Number of tokens to generate
|
335 |
+
# temperature: Sampling temperature (higher = more random)
|
336 |
+
|
337 |
+
# Returns:
|
338 |
+
# Generated token sequence
|
339 |
+
# """
|
340 |
+
# for _ in range(max_new_tokens):
|
341 |
+
# # Crop context if needed
|
342 |
+
# idx_cond = input_ids[:, -self.block_size :]
|
343 |
+
# # Get predictions
|
344 |
+
# logits, _ = self(idx_cond)
|
345 |
+
# # Focus only on the last time step
|
346 |
+
# logits = logits[:, -1, :] / temperature
|
347 |
+
# # Apply softmax to get probabilities
|
348 |
+
# probs = F.softmax(logits, dim=-1)
|
349 |
+
# # Sample from the distribution
|
350 |
+
# idx_next = torch.multinomial(probs, num_samples=1)
|
351 |
+
# # Append sampled index to the running sequence
|
352 |
+
# idx = torch.cat((idx, idx_next), dim=1)
|
353 |
+
# return idx
|