Upload model
Browse files- README.md +199 -0
- config.json +19 -0
- model.py +608 -0
- model.safetensors +3 -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 |
+
"LightGPTHuggingFaceModel"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "model.LightGPTHuggingFaceConfig",
|
7 |
+
"AutoModel": "model.LightGPTHuggingFaceModel"
|
8 |
+
},
|
9 |
+
"dropout": 0.1,
|
10 |
+
"embedding_dimensions": 1024,
|
11 |
+
"feed_forward_ratio": 4,
|
12 |
+
"model_type": "lightgpt",
|
13 |
+
"num_heads": 16,
|
14 |
+
"num_layers": 24,
|
15 |
+
"padding_index": -100,
|
16 |
+
"torch_dtype": "float32",
|
17 |
+
"transformers_version": "4.49.0",
|
18 |
+
"vocabulary_size": 50257
|
19 |
+
}
|
model.py
ADDED
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from math import sqrt
|
2 |
+
from dataclasses import dataclass
|
3 |
+
from functools import partial, cached_property
|
4 |
+
from typing import Iterator, Self
|
5 |
+
|
6 |
+
import torch
|
7 |
+
|
8 |
+
from torch import Tensor
|
9 |
+
from torch.nn import (
|
10 |
+
Module,
|
11 |
+
ModuleList,
|
12 |
+
Sequential,
|
13 |
+
Embedding,
|
14 |
+
MultiheadAttention,
|
15 |
+
Linear,
|
16 |
+
SiLU,
|
17 |
+
RMSNorm,
|
18 |
+
Dropout1d,
|
19 |
+
CrossEntropyLoss,
|
20 |
+
Parameter,
|
21 |
+
)
|
22 |
+
|
23 |
+
from torch.nn.functional import softmax, log_softmax
|
24 |
+
from torch.nn.utils.parametrize import register_parametrization, remove_parametrizations
|
25 |
+
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
26 |
+
|
27 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
28 |
+
|
29 |
+
|
30 |
+
class LightGPT(Module):
|
31 |
+
"""A generative pretrained transformer with no positional embeddings."""
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
vocabulary_size: int,
|
36 |
+
embedding_dimensions: int,
|
37 |
+
num_heads: int,
|
38 |
+
num_layers: int,
|
39 |
+
feed_forward_ratio: int,
|
40 |
+
dropout: float,
|
41 |
+
padding_index: int,
|
42 |
+
):
|
43 |
+
super().__init__()
|
44 |
+
|
45 |
+
if vocabulary_size <= 0:
|
46 |
+
raise ValueError(
|
47 |
+
f"Vocabulary size must be greater than 0, {vocabulary_size} given."
|
48 |
+
)
|
49 |
+
|
50 |
+
if num_layers <= 0:
|
51 |
+
raise ValueError(f"Num layers must be greater than 0, {num_layers} given.")
|
52 |
+
|
53 |
+
if feed_forward_ratio not in {1, 2, 4}:
|
54 |
+
raise ValueError("Feed-forward ratio must be either 1, 2, or 4.")
|
55 |
+
|
56 |
+
token_embeddings = Embedding(
|
57 |
+
vocabulary_size, embedding_dimensions, padding_idx=padding_index
|
58 |
+
)
|
59 |
+
|
60 |
+
output_layer = Linear(embedding_dimensions, vocabulary_size, bias=False)
|
61 |
+
|
62 |
+
output_layer.weight = token_embeddings.weight # Tie weights
|
63 |
+
|
64 |
+
self.token_embeddings = token_embeddings
|
65 |
+
|
66 |
+
self.body = ModuleList(
|
67 |
+
[
|
68 |
+
CausalSelfAttentionBlock(
|
69 |
+
embedding_dimensions,
|
70 |
+
num_heads,
|
71 |
+
feed_forward_ratio,
|
72 |
+
dropout,
|
73 |
+
)
|
74 |
+
for _ in range(num_layers)
|
75 |
+
]
|
76 |
+
)
|
77 |
+
|
78 |
+
self.checkpoint = lambda layer, x, attention_mask: layer(x, attention_mask)
|
79 |
+
|
80 |
+
self.output_norm = RMSNorm(embedding_dimensions)
|
81 |
+
self.output_layer = output_layer
|
82 |
+
|
83 |
+
self.loss_function = CrossEntropyLoss(ignore_index=padding_index)
|
84 |
+
|
85 |
+
self.vocabulary_size = vocabulary_size
|
86 |
+
|
87 |
+
@cached_property
|
88 |
+
def num_trainable_params(self) -> int:
|
89 |
+
return sum(param.numel() for param in self.parameters() if param.requires_grad)
|
90 |
+
|
91 |
+
def enable_activation_checkpointing(self) -> None:
|
92 |
+
"""Instead of memorizing the activations of the forward pass, recompute them at various checkpoints."""
|
93 |
+
self.checkpoint = partial(torch_checkpoint, use_reentrant=False)
|
94 |
+
|
95 |
+
def freeze_model_parameters(self) -> Self:
|
96 |
+
"""Freeze all model parameters to prevent them from being updated during training."""
|
97 |
+
|
98 |
+
for param in self.parameters():
|
99 |
+
param.requires_grad = False
|
100 |
+
|
101 |
+
return self
|
102 |
+
|
103 |
+
def unfreeze_token_embeddings(self) -> Self:
|
104 |
+
"""Unfreeze the token embeddings to allow for fine-tuning."""
|
105 |
+
|
106 |
+
for param in self.token_embeddings.parameters():
|
107 |
+
param.requires_grad = True
|
108 |
+
|
109 |
+
return self
|
110 |
+
|
111 |
+
@torch.no_grad()
|
112 |
+
def resize_token_embeddings(self, vocabulary_size: int) -> Self:
|
113 |
+
"""Resize the token embeddings to accommodate a new vocabulary size."""
|
114 |
+
|
115 |
+
if vocabulary_size <= 0:
|
116 |
+
raise ValueError(
|
117 |
+
f"Vocabulary size must be greater than 0, {vocabulary_size} given."
|
118 |
+
)
|
119 |
+
|
120 |
+
new_embeddings = Embedding(
|
121 |
+
vocabulary_size, self.token_embeddings.embedding_dim
|
122 |
+
).to(self.token_embeddings.weight.device)
|
123 |
+
|
124 |
+
num_tokens_to_copy = min(vocabulary_size, self.token_embeddings.num_embeddings)
|
125 |
+
|
126 |
+
new_embeddings.weight[:num_tokens_to_copy, :] = self.token_embeddings.weight[
|
127 |
+
:num_tokens_to_copy, :
|
128 |
+
]
|
129 |
+
|
130 |
+
for i in range(num_tokens_to_copy, vocabulary_size):
|
131 |
+
new_embeddings.weight[i] = torch.randn(new_embeddings.embedding_dim) / sqrt(
|
132 |
+
new_embeddings.embedding_dim
|
133 |
+
)
|
134 |
+
|
135 |
+
self.token_embeddings.weight = new_embeddings.weight
|
136 |
+
self.token_embeddings.num_embeddings = new_embeddings.num_embeddings
|
137 |
+
|
138 |
+
self.output_layer.weight = self.token_embeddings.weight
|
139 |
+
|
140 |
+
self.vocabulary_size = vocabulary_size
|
141 |
+
|
142 |
+
return self
|
143 |
+
|
144 |
+
def add_lora_parameters(self, rank: int, alpha: float, dropout: float) -> Self:
|
145 |
+
"""Reparameterize the weights of the model using LoRA."""
|
146 |
+
|
147 |
+
for module in self.body:
|
148 |
+
out_features, in_features = module.attention.in_proj_weight.shape
|
149 |
+
|
150 |
+
register_parametrization(
|
151 |
+
module.attention,
|
152 |
+
"in_proj_weight",
|
153 |
+
LoRA(in_features, out_features, rank, alpha, dropout),
|
154 |
+
)
|
155 |
+
|
156 |
+
out_features, in_features = module.attention.out_proj.weight.shape
|
157 |
+
|
158 |
+
register_parametrization(
|
159 |
+
module.attention.out_proj,
|
160 |
+
"weight",
|
161 |
+
LoRA(in_features, out_features, rank, alpha, dropout),
|
162 |
+
)
|
163 |
+
|
164 |
+
for layer in module.mlp.layers:
|
165 |
+
if isinstance(layer, Linear):
|
166 |
+
register_parametrization(
|
167 |
+
layer,
|
168 |
+
"weight",
|
169 |
+
LoRA.from_linear(layer, rank, alpha, dropout),
|
170 |
+
)
|
171 |
+
|
172 |
+
return self
|
173 |
+
|
174 |
+
def lora_state_dict(self) -> dict[str, Tensor]:
|
175 |
+
"""Return a state dict containing only the LoRA parameters."""
|
176 |
+
|
177 |
+
return {
|
178 |
+
name: module
|
179 |
+
for name, module in self.state_dict().items()
|
180 |
+
if "lora" in name
|
181 |
+
}
|
182 |
+
|
183 |
+
def merge_lora_parameters(self) -> Self:
|
184 |
+
"""Merge the LoRA parameters with the original parameters."""
|
185 |
+
|
186 |
+
for module in self.body:
|
187 |
+
if hasattr(module, "parametrizations"):
|
188 |
+
lora_params = [name for name in module.parametrizations.keys()]
|
189 |
+
|
190 |
+
for name in lora_params:
|
191 |
+
remove_parametrizations(module, name, leave_parametrized=True)
|
192 |
+
|
193 |
+
return self
|
194 |
+
|
195 |
+
def forward(
|
196 |
+
self, x: Tensor, y: Tensor | None = None
|
197 |
+
) -> tuple[Tensor, Tensor | None]:
|
198 |
+
"""A forward pass optimized for batch training."""
|
199 |
+
|
200 |
+
z = self.token_embeddings(x)
|
201 |
+
|
202 |
+
b, t, d = z.size()
|
203 |
+
|
204 |
+
causal_mask = torch.full((t, t), float("-inf"), dtype=z.dtype, device=z.device)
|
205 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
206 |
+
|
207 |
+
for layer in self.body:
|
208 |
+
z = self.checkpoint(layer, z, causal_mask)
|
209 |
+
|
210 |
+
z = self.output_norm(z)
|
211 |
+
z = self.output_layer(z)
|
212 |
+
|
213 |
+
if y is not None:
|
214 |
+
y_pred = z.view(-1, z.size(-1))
|
215 |
+
labels = y.view(-1) # Flatten the batch dimension.
|
216 |
+
|
217 |
+
loss = self.loss_function(y_pred, labels)
|
218 |
+
else:
|
219 |
+
loss = None
|
220 |
+
|
221 |
+
return z, loss
|
222 |
+
|
223 |
+
@torch.no_grad()
|
224 |
+
def predict(self, x: Tensor) -> Tensor:
|
225 |
+
"""A forward pass optimized for batch next-token prediction."""
|
226 |
+
|
227 |
+
z = self.token_embeddings(x)
|
228 |
+
|
229 |
+
b, t, d = z.size()
|
230 |
+
|
231 |
+
causal_mask = torch.full((t, t), float("-inf"), dtype=z.dtype, device=z.device)
|
232 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
233 |
+
|
234 |
+
for layer in self.body:
|
235 |
+
z = layer(z, causal_mask)
|
236 |
+
|
237 |
+
z = self.output_norm(z)
|
238 |
+
|
239 |
+
z = z[:, -1, :] # Pluck only the last token embedding from each batch.
|
240 |
+
|
241 |
+
z = self.output_layer(z)
|
242 |
+
|
243 |
+
return z
|
244 |
+
|
245 |
+
@torch.no_grad()
|
246 |
+
def generate(
|
247 |
+
self,
|
248 |
+
prompt: Tensor,
|
249 |
+
max_tokens: int = 1000,
|
250 |
+
context_length: int = 1024,
|
251 |
+
temperature: float = 1.0,
|
252 |
+
top_k: int = 500,
|
253 |
+
top_p: float = 0.9,
|
254 |
+
eos_indices: set = set(),
|
255 |
+
) -> Iterator:
|
256 |
+
"""
|
257 |
+
Given a prompt, sample the next {max_tokens} tokens from the model weighted
|
258 |
+
by their predicted probabilities and filtered by the {top_k} and {top_p}.
|
259 |
+
"""
|
260 |
+
|
261 |
+
if max_tokens <= 0:
|
262 |
+
raise ValueError(f"Max tokens must be greater than 0, {max_tokens} given.")
|
263 |
+
|
264 |
+
if temperature <= 0:
|
265 |
+
raise ValueError(
|
266 |
+
f"Temperature must be greater than 0, {temperature} given."
|
267 |
+
)
|
268 |
+
|
269 |
+
if top_k <= 0 or top_k > self.vocabulary_size:
|
270 |
+
raise ValueError(
|
271 |
+
f"Top k must be between 1 and {self.vocabulary_size}, {top_k} given."
|
272 |
+
)
|
273 |
+
|
274 |
+
if top_p <= 0.0 or top_p > 1.0:
|
275 |
+
raise ValueError(f"Top p must be between 0 and 1, {top_p} given.")
|
276 |
+
|
277 |
+
context_window = prompt
|
278 |
+
|
279 |
+
for _ in range(max_tokens):
|
280 |
+
context_window = context_window[-context_length:]
|
281 |
+
|
282 |
+
logits = self.predict(context_window.unsqueeze(0)).squeeze()
|
283 |
+
|
284 |
+
logits, indices = torch.topk(logits, top_k, sorted=True)
|
285 |
+
|
286 |
+
probabilities = softmax(logits, dim=0)
|
287 |
+
|
288 |
+
cumulative_probability_mass = torch.cumsum(probabilities, dim=0)
|
289 |
+
|
290 |
+
min_probability_mass = cumulative_probability_mass[0]
|
291 |
+
|
292 |
+
threshold_p = max(top_p, min_probability_mass.item())
|
293 |
+
|
294 |
+
selected_indices = cumulative_probability_mass <= threshold_p
|
295 |
+
|
296 |
+
logits = logits[selected_indices]
|
297 |
+
indices = indices[selected_indices]
|
298 |
+
|
299 |
+
logits /= temperature
|
300 |
+
|
301 |
+
probabilities = softmax(logits, dim=0)
|
302 |
+
|
303 |
+
offset = torch.multinomial(probabilities, num_samples=1).squeeze()
|
304 |
+
|
305 |
+
next_token = indices[offset]
|
306 |
+
|
307 |
+
if next_token.item() in eos_indices:
|
308 |
+
break
|
309 |
+
|
310 |
+
yield next_token
|
311 |
+
|
312 |
+
context_window = torch.cat((context_window, next_token.unsqueeze(0)))
|
313 |
+
|
314 |
+
@torch.no_grad()
|
315 |
+
def beam_search(
|
316 |
+
self,
|
317 |
+
prompt: Tensor,
|
318 |
+
max_tokens: int = 100,
|
319 |
+
context_length: int = 1024,
|
320 |
+
num_candidates: int = 3,
|
321 |
+
beam_width: int = 16,
|
322 |
+
length_penalty: float = 1.0,
|
323 |
+
eos_indices: set = set(),
|
324 |
+
) -> list:
|
325 |
+
"""
|
326 |
+
Given a prompt, return the {num_candidates} highest probability sequences. Note that
|
327 |
+
this method is often best for generating shorter sequences and is typically less
|
328 |
+
natural sounding than sequences that are more random in nature.
|
329 |
+
"""
|
330 |
+
|
331 |
+
if max_tokens <= 0:
|
332 |
+
raise ValueError(f"Max tokens must be greater than 0, {max_tokens} given.")
|
333 |
+
|
334 |
+
if num_candidates <= 0:
|
335 |
+
raise ValueError(
|
336 |
+
f"Num candidates must be greater than 0, {num_candidates} given."
|
337 |
+
)
|
338 |
+
|
339 |
+
if beam_width <= 0:
|
340 |
+
raise ValueError(f"Beam width must be greater than 0, {beam_width} given.")
|
341 |
+
|
342 |
+
if length_penalty <= 0:
|
343 |
+
raise ValueError(
|
344 |
+
f"Length penalty must be greater than 0, {length_penalty} given."
|
345 |
+
)
|
346 |
+
|
347 |
+
@dataclass
|
348 |
+
class Candidate:
|
349 |
+
cumulative_log_probability: float
|
350 |
+
tokens: Tensor
|
351 |
+
|
352 |
+
def priority(self) -> float:
|
353 |
+
return (
|
354 |
+
self.cumulative_log_probability / len(self.tokens) ** length_penalty
|
355 |
+
)
|
356 |
+
|
357 |
+
sort_candidates = partial(
|
358 |
+
sorted,
|
359 |
+
key=lambda candidate: candidate.priority(),
|
360 |
+
reverse=True,
|
361 |
+
)
|
362 |
+
|
363 |
+
candidates: list[Candidate] = []
|
364 |
+
completed: list[Candidate] = []
|
365 |
+
|
366 |
+
tokens = torch.tensor([], dtype=prompt.dtype).to(prompt.device)
|
367 |
+
|
368 |
+
candidates.append(Candidate(0.0, tokens))
|
369 |
+
|
370 |
+
while len(candidates) > 0:
|
371 |
+
candidate = candidates.pop()
|
372 |
+
|
373 |
+
if len(completed) >= num_candidates:
|
374 |
+
completed = sort_candidates(completed)
|
375 |
+
|
376 |
+
completed = completed[:num_candidates]
|
377 |
+
|
378 |
+
worst_candidate = completed[-1]
|
379 |
+
|
380 |
+
if (
|
381 |
+
candidate.cumulative_log_probability
|
382 |
+
< worst_candidate.cumulative_log_probability
|
383 |
+
):
|
384 |
+
break
|
385 |
+
|
386 |
+
if len(candidate.tokens) > 0:
|
387 |
+
last_token = candidate.tokens[-1]
|
388 |
+
|
389 |
+
if last_token.item() in eos_indices:
|
390 |
+
candidate.tokens = candidate.tokens[:-1]
|
391 |
+
|
392 |
+
completed.append(candidate)
|
393 |
+
|
394 |
+
continue
|
395 |
+
|
396 |
+
if len(candidate.tokens) >= max_tokens:
|
397 |
+
completed.append(candidate)
|
398 |
+
|
399 |
+
continue
|
400 |
+
|
401 |
+
context_window = torch.cat((prompt, candidate.tokens))
|
402 |
+
|
403 |
+
context_window = context_window[-context_length:]
|
404 |
+
|
405 |
+
logits = self.predict(context_window.unsqueeze(0)).squeeze()
|
406 |
+
|
407 |
+
logits, indices = torch.topk(logits, beam_width, sorted=False)
|
408 |
+
|
409 |
+
log_probabilities = log_softmax(logits, dim=0)
|
410 |
+
|
411 |
+
for log_probability, index in zip(log_probabilities, indices):
|
412 |
+
cumulative_log_probability = (
|
413 |
+
candidate.cumulative_log_probability + log_probability
|
414 |
+
)
|
415 |
+
|
416 |
+
tokens = torch.cat((candidate.tokens, index.unsqueeze(0)))
|
417 |
+
|
418 |
+
candidates.append(Candidate(cumulative_log_probability, tokens))
|
419 |
+
|
420 |
+
candidates = sort_candidates(candidates)
|
421 |
+
|
422 |
+
candidates = candidates[:beam_width]
|
423 |
+
|
424 |
+
return completed
|
425 |
+
|
426 |
+
|
427 |
+
class LightGPTHuggingFaceConfig(PretrainedConfig):
|
428 |
+
"""Provide a monolithic configuration object to compensate for HuggingFace Transformers' API."""
|
429 |
+
|
430 |
+
model_type = "lightgpt"
|
431 |
+
|
432 |
+
def __init__(
|
433 |
+
self,
|
434 |
+
vocabulary_size: int = 50257,
|
435 |
+
embedding_dimensions: int = 1024,
|
436 |
+
num_heads: int = 16,
|
437 |
+
num_layers: int = 24,
|
438 |
+
feed_forward_ratio: int = 4,
|
439 |
+
dropout: float = 0.1,
|
440 |
+
padding_index: int = -100,
|
441 |
+
**kwargs,
|
442 |
+
):
|
443 |
+
self.vocabulary_size = vocabulary_size
|
444 |
+
self.embedding_dimensions = embedding_dimensions
|
445 |
+
self.num_heads = num_heads
|
446 |
+
self.num_layers = num_layers
|
447 |
+
self.feed_forward_ratio = feed_forward_ratio
|
448 |
+
self.dropout = dropout
|
449 |
+
self.padding_index = padding_index
|
450 |
+
|
451 |
+
super().__init__(**kwargs)
|
452 |
+
|
453 |
+
|
454 |
+
class LightGPTHuggingFaceModel(PreTrainedModel):
|
455 |
+
"""Compensate for HuggingFace Transformers' API using a model wrapper."""
|
456 |
+
|
457 |
+
config_class = LightGPTHuggingFaceConfig
|
458 |
+
|
459 |
+
def __init__(self, config: LightGPTHuggingFaceConfig):
|
460 |
+
super().__init__(config)
|
461 |
+
|
462 |
+
self.model = LightGPT(
|
463 |
+
config.vocabulary_size,
|
464 |
+
config.embedding_dimensions,
|
465 |
+
config.num_heads,
|
466 |
+
config.num_layers,
|
467 |
+
config.feed_forward_ratio,
|
468 |
+
config.dropout,
|
469 |
+
config.padding_index,
|
470 |
+
)
|
471 |
+
|
472 |
+
def forward(
|
473 |
+
self, x: Tensor, y: Tensor | None = None
|
474 |
+
) -> tuple[Tensor, Tensor | None]:
|
475 |
+
logits, loss = self.model.forward(x, y)
|
476 |
+
|
477 |
+
return {
|
478 |
+
"logits": logits,
|
479 |
+
"loss": loss,
|
480 |
+
}
|
481 |
+
|
482 |
+
|
483 |
+
class CausalSelfAttentionBlock(Module):
|
484 |
+
"""Causal self-attention block with residual connections."""
|
485 |
+
|
486 |
+
def __init__(
|
487 |
+
self,
|
488 |
+
embedding_dimensions: int,
|
489 |
+
num_heads: int,
|
490 |
+
feed_forward_ratio: int,
|
491 |
+
dropout: float,
|
492 |
+
):
|
493 |
+
super().__init__()
|
494 |
+
|
495 |
+
if embedding_dimensions <= 0:
|
496 |
+
raise ValueError(
|
497 |
+
f"Embedding dimensions must be greater than 0, {embedding_dimensions} given."
|
498 |
+
)
|
499 |
+
|
500 |
+
if num_heads <= 0:
|
501 |
+
raise ValueError(f"Num heads must be greater than 0, {num_heads} given.")
|
502 |
+
|
503 |
+
if dropout < 0 or dropout > 1:
|
504 |
+
raise ValueError(f"Dropout must be between 0 and 1, {dropout} given")
|
505 |
+
|
506 |
+
self.norm1 = RMSNorm(embedding_dimensions)
|
507 |
+
self.attention = MultiheadAttention(
|
508 |
+
embedding_dimensions,
|
509 |
+
num_heads,
|
510 |
+
batch_first=True,
|
511 |
+
dropout=dropout,
|
512 |
+
bias=False,
|
513 |
+
)
|
514 |
+
|
515 |
+
hidden_dimensions = feed_forward_ratio * embedding_dimensions
|
516 |
+
|
517 |
+
self.norm2 = RMSNorm(embedding_dimensions)
|
518 |
+
self.mlp = MLP(embedding_dimensions, hidden_dimensions, dropout)
|
519 |
+
|
520 |
+
def forward(self, x: Tensor, attention_mask: Tensor) -> Tensor:
|
521 |
+
z = self.norm1(x)
|
522 |
+
z, _ = self.attention(z, z, z, attn_mask=attention_mask, is_causal=True)
|
523 |
+
|
524 |
+
z = x + z # Residual connection
|
525 |
+
|
526 |
+
x = z
|
527 |
+
|
528 |
+
z = self.norm2(x)
|
529 |
+
z = self.mlp(z)
|
530 |
+
|
531 |
+
z = x + z # Residual connection
|
532 |
+
|
533 |
+
return z
|
534 |
+
|
535 |
+
|
536 |
+
class MLP(Module):
|
537 |
+
"""A two-layer fully-connected network with dropout."""
|
538 |
+
|
539 |
+
def __init__(
|
540 |
+
self, embedding_dimensions: int, hidden_dimensions: int, dropout: float
|
541 |
+
):
|
542 |
+
super().__init__()
|
543 |
+
|
544 |
+
if embedding_dimensions <= 0:
|
545 |
+
raise ValueError(
|
546 |
+
f"Embedding dimensions must be greater than 0, {embedding_dimensions} given."
|
547 |
+
)
|
548 |
+
|
549 |
+
if hidden_dimensions <= 0:
|
550 |
+
raise ValueError(
|
551 |
+
f"Hidden dimensions must be greater than 0, {hidden_dimensions} given."
|
552 |
+
)
|
553 |
+
|
554 |
+
self.layers = Sequential(
|
555 |
+
Linear(embedding_dimensions, hidden_dimensions, bias=False),
|
556 |
+
SiLU(),
|
557 |
+
Linear(hidden_dimensions, embedding_dimensions, bias=False),
|
558 |
+
)
|
559 |
+
|
560 |
+
self.dropout = Dropout1d(p=dropout)
|
561 |
+
|
562 |
+
def forward(self, x: Tensor) -> Tensor:
|
563 |
+
return self.dropout(self.layers(x))
|
564 |
+
|
565 |
+
|
566 |
+
class LoRA(Module):
|
567 |
+
"""Rank decomposition transformation."""
|
568 |
+
|
569 |
+
@classmethod
|
570 |
+
def from_linear(
|
571 |
+
cls, linear: Linear, rank: int, alpha: float, dropout: float
|
572 |
+
) -> Self:
|
573 |
+
out_features, in_features = linear.weight.shape
|
574 |
+
|
575 |
+
return cls(in_features, out_features, rank, alpha, dropout)
|
576 |
+
|
577 |
+
def __init__(
|
578 |
+
self,
|
579 |
+
in_features: int,
|
580 |
+
out_features: int,
|
581 |
+
rank: int,
|
582 |
+
alpha: float,
|
583 |
+
dropout: float,
|
584 |
+
):
|
585 |
+
super().__init__()
|
586 |
+
|
587 |
+
if rank <= 0:
|
588 |
+
raise ValueError(f"Rank must be greater than 0, {rank} given.")
|
589 |
+
|
590 |
+
if alpha <= 0.0:
|
591 |
+
raise ValueError(f"Alpha must be greater than 0, {alpha} given.")
|
592 |
+
|
593 |
+
if dropout < 0 or dropout > 1:
|
594 |
+
raise ValueError(f"Dropout must be between 0 and 1, {dropout} given")
|
595 |
+
|
596 |
+
self.lora_a = Parameter(torch.randn(rank, in_features) / sqrt(rank))
|
597 |
+
self.lora_b = Parameter(torch.zeros(out_features, rank))
|
598 |
+
|
599 |
+
self.dropout = Dropout1d(dropout)
|
600 |
+
|
601 |
+
self.alpha = alpha
|
602 |
+
|
603 |
+
def forward(self, x: Tensor) -> Tensor:
|
604 |
+
z = self.lora_b @ self.dropout(self.lora_a)
|
605 |
+
|
606 |
+
z *= self.alpha
|
607 |
+
|
608 |
+
return x + z
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8408c3f7c282506d3d6ac2d2ca86a50520de2ff8e6569a97a011b0dce92b08cd
|
3 |
+
size 1426645912
|