samkeet commited on
Commit
f721159
·
verified ·
1 Parent(s): 51b21a5

Upload model

Browse files
Files changed (6) hide show
  1. README.md +199 -0
  2. config.json +17 -0
  3. configuration_gpt.py +25 -0
  4. generation_config.json +4 -0
  5. modeling_gpt.py +289 -0
  6. pytorch_model.bin +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,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GPTModelForTextGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_gpt.GPTConfig",
7
+ "AutoModelForCausalLM": "modeling_gpt.GPTModelForTextGeneration"
8
+ },
9
+ "block_size": 1024,
10
+ "model_type": "custom_gpt",
11
+ "n_embd": 768,
12
+ "n_head": 12,
13
+ "n_layer": 12,
14
+ "torch_dtype": "float32",
15
+ "transformers_version": "4.44.1",
16
+ "vocab_size": 50304
17
+ }
configuration_gpt.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing libraries
2
+ from transformers import PretrainedConfig
3
+
4
+
5
+ class GPTConfig(PretrainedConfig):
6
+ model_type = "custom_gpt"
7
+
8
+ def __init__(
9
+ self,
10
+ block_size: int = 1024,
11
+ vocab_size: int = 50304,
12
+ n_layer: int = 12,
13
+ n_head: int = 12,
14
+ n_embd: int = 768,
15
+ **kwargs,
16
+ ):
17
+ """
18
+ GPT configuration dataclass storing model hyperparameters.
19
+ """
20
+ super().__init__(**kwargs)
21
+ self.block_size = block_size
22
+ self.vocab_size = vocab_size
23
+ self.n_layer: int = n_layer
24
+ self.n_head: int = n_head
25
+ self.n_embd: int = n_embd
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.44.1"
4
+ }
modeling_gpt.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importing libraries
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from transformers import PreTrainedModel
6
+ from .configuration_gpt import GPTConfig
7
+
8
+
9
+ class GPT(nn.Module):
10
+ """
11
+ The GPT language model:
12
+ - Embeddings (token + positional)
13
+ - Stack of Transformer blocks
14
+ - Final LayerNorm + Linear head for output logits
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ block_size: int = 1024,
20
+ vocab_size: int = 50304,
21
+ n_layer: int = 12,
22
+ n_head: int = 12,
23
+ n_embd: int = 768,
24
+ ):
25
+ super().__init__()
26
+
27
+ # Store model hyperparameters
28
+ self.block_size = block_size
29
+ self.vocab_size = vocab_size
30
+ self.n_layer = n_layer
31
+ self.n_head = n_head
32
+ self.n_embd = n_embd
33
+
34
+ # Transformer components stored in a module dictionary
35
+ self.transformer = nn.ModuleDict(
36
+ dict(
37
+ wte=nn.Embedding(self.vocab_size, self.n_embd), # Token embedding
38
+ wpe=nn.Embedding(self.block_size, self.n_embd), # Positional embedding
39
+ h=nn.ModuleList(
40
+ [self.Block(self.n_embd, self.n_head) for _ in range(self.n_layer)]
41
+ ), # Transformer blocks
42
+ ln_f=nn.LayerNorm(self.n_embd), # Final layer normalization
43
+ )
44
+ )
45
+
46
+ # Linear head for output logits
47
+ self.lm_head = nn.Linear(self.n_embd, self.vocab_size, bias=False)
48
+
49
+ # Tie weights between token embedding and output projection
50
+ self.transformer.wte.weight = self.lm_head.weight
51
+
52
+ def forward(self, x):
53
+ B, T = x.shape # Batch size and sequence length
54
+ assert T <= self.block_size, "Cannot forward sequence longer than block size"
55
+
56
+ # Token and positional embeddings
57
+ tok_emb = self.transformer.wte(x)
58
+ pos_emb = self.transformer.wpe(torch.arange(T, device=x.device))
59
+ x = tok_emb + pos_emb.unsqueeze(0)
60
+
61
+ # Forward pass through transformer blocks
62
+ for block in self.transformer.h:
63
+ x = block(x)
64
+
65
+ x = self.transformer.ln_f(x) # Final layer norm
66
+ logits = self.lm_head(x) # Compute logits
67
+ return logits
68
+
69
+ class CausalSelfAttention(nn.Module):
70
+ """
71
+ Multi-head self-attention with causal masking.
72
+ """
73
+
74
+ def __init__(self, n_embd, n_head):
75
+ super().__init__()
76
+ assert (
77
+ n_embd % n_head == 0
78
+ ), "Embedding dimension must be divisible by number of heads"
79
+ self.n_head = n_head
80
+ self.n_embd = n_embd
81
+
82
+ # Linear layers for query, key, and value
83
+ self.c_attn = nn.Linear(n_embd, 3 * n_embd)
84
+ self.c_proj = nn.Linear(n_embd, n_embd)
85
+
86
+ def forward(self, x):
87
+ B, T, C = x.size()
88
+ qkv = self.c_attn(x)
89
+ q, k, v = qkv.split(self.n_embd, dim=2)
90
+
91
+ # Reshape and transpose for multi-head attention
92
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
93
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
94
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
95
+
96
+ # Apply scaled dot-product attention with causal masking
97
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
98
+
99
+ # Reshape and apply output projection
100
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
101
+ y = self.c_proj(y)
102
+ return y
103
+
104
+ class MLP(nn.Module):
105
+ """
106
+ Feed-forward network block used in Transformer architectures.
107
+ """
108
+
109
+ def __init__(self, n_embd):
110
+ super().__init__()
111
+ self.c_fc = nn.Linear(n_embd, 4 * n_embd)
112
+ self.gelu = nn.GELU(approximate="tanh")
113
+ self.c_proj = nn.Linear(4 * n_embd, n_embd)
114
+
115
+ def forward(self, x):
116
+ return self.c_proj(self.gelu(self.c_fc(x)))
117
+
118
+ class Block(nn.Module):
119
+ """
120
+ A single Transformer block.
121
+ """
122
+
123
+ def __init__(self, n_embd, n_head):
124
+ super().__init__()
125
+ self.ln_1 = nn.LayerNorm(n_embd)
126
+ self.attn = GPT.CausalSelfAttention(n_embd, n_head)
127
+ self.ln_2 = nn.LayerNorm(n_embd)
128
+ self.mlp = GPT.MLP(n_embd)
129
+
130
+ def forward(self, x):
131
+ x = x + self.attn(self.ln_1(x))
132
+ x = x + self.mlp(self.ln_2(x))
133
+ return x
134
+
135
+
136
+ class GPTModelForTextGeneration(PreTrainedModel):
137
+ """
138
+ A wrapper class for GPT-based text generation.
139
+ This integrates a Transformer model within the Hugging Face `PreTrainedModel` framework.
140
+ """
141
+
142
+ config_class = GPTConfig
143
+
144
+ def __init__(self, config):
145
+ super().__init__(config)
146
+
147
+ # Instantiate the GPT model with the provided configuration
148
+ self.model = GPT(
149
+ block_size=config.block_size,
150
+ vocab_size=config.vocab_size,
151
+ n_layer=config.n_layer,
152
+ n_head=config.n_head,
153
+ n_embd=config.n_embd,
154
+ )
155
+
156
+ def forward(self, input_ids: torch.Tensor):
157
+ # Check input_ids type and shape
158
+ assert isinstance(input_ids, torch.Tensor), "input_ids must be a PyTorch tensor"
159
+
160
+ tokens = input_ids.clone() # Avoid modifying input_ids directly
161
+ tokens = tokens.unsqueeze(0) if tokens.dim() == 1 else tokens
162
+
163
+ assert (
164
+ tokens.ndim == 2 and tokens.shape[0] == 1
165
+ ), "input_ids must have 2 dimensions: (1, sequence_length)"
166
+
167
+ # Check token values
168
+ assert torch.all(
169
+ (tokens >= 0) & (tokens <= self.model.vocab_size)
170
+ ), "input_ids contain invalid token values"
171
+
172
+ # Forward pass through the model
173
+ logits = self.model.forward(tokens)
174
+
175
+ return {"logits": logits}
176
+
177
+ @torch.no_grad()
178
+ def generate(
179
+ self,
180
+ input_ids: torch.Tensor,
181
+ max_length: int = 50,
182
+ do_sample: bool = True,
183
+ top_k: int = 50,
184
+ top_p: float = 0.95,
185
+ temperature: float = 0.9,
186
+ device: str = "cpu",
187
+ ):
188
+ """
189
+ Generates text using autoregressive sampling with top-k, top-p, and temperature.
190
+ """
191
+
192
+ # Validate device type
193
+ if device.startswith("cuda"):
194
+ assert torch.cuda.is_available(), "CUDA is not available, please use 'cpu'"
195
+ if device != "cuda": # Check for specific CUDA device (cuda:n)
196
+ try:
197
+ device_index = int(device.split(":")[1]) # Extract device number
198
+ assert (
199
+ 0 <= device_index < torch.cuda.device_count()
200
+ ), f"Invalid CUDA device index: {device_index}"
201
+ except (IndexError, ValueError):
202
+ raise ValueError(
203
+ "Invalid device format. Use 'cpu', 'cuda', or 'cuda:N' where N is an integer."
204
+ )
205
+ elif device != "cpu":
206
+ raise ValueError("Invalid device. Use 'cpu', 'cuda', or 'cuda:N'.")
207
+
208
+ # Move input tensor and model to the specified device
209
+ input_ids = input_ids.to(device)
210
+ self.model.to(device)
211
+
212
+ # Check input_ids type and shape
213
+ assert isinstance(input_ids, torch.Tensor), "input_ids must be a PyTorch tensor"
214
+ tokens = input_ids.clone() # Avoid modifying input_ids directly
215
+ tokens = tokens.unsqueeze(0) if tokens.dim() == 1 else tokens
216
+
217
+ assert (
218
+ tokens.ndim == 2 and tokens.shape[0] == 1
219
+ ), "input_ids must have 2 dimensions: (1, sequence_length)"
220
+
221
+ # Check token values
222
+ assert torch.all(
223
+ (tokens >= 0) & (tokens < self.model.vocab_size)
224
+ ), "input_ids contain invalid token values"
225
+
226
+ # Check max_length
227
+ assert (
228
+ isinstance(max_length, int) and max_length >= 1
229
+ ), "max_length must be a positive integer"
230
+ assert (
231
+ max_length <= self.model.block_size
232
+ ), f"max_length must be in range [1, {self.model.block_size}]"
233
+
234
+ # Check top_k
235
+ assert isinstance(top_k, int) and top_k >= 1, "top_k must be a positive integer"
236
+
237
+ # Check top_p
238
+ assert (
239
+ isinstance(top_p, (int, float)) and 0.0 <= top_p <= 1.0
240
+ ), "top_p must be in range [0, 1]"
241
+
242
+ # Check temperature
243
+ assert (
244
+ isinstance(temperature, (int, float)) and 0.0 <= temperature <= 1.0
245
+ ), "temperature must be in range [0, 1]"
246
+
247
+ # Move tokens to the correct device
248
+ tokens = tokens.to(device)
249
+
250
+ # Autoregressive token generation loop
251
+ while tokens.size(1) < max_length:
252
+ logits = self.forward(tokens)["logits"][:, -1, :]
253
+ logits = logits / max(0.01, temperature)
254
+
255
+ if do_sample:
256
+ top_k = min(top_k, logits.size(-1)) # Safety check
257
+
258
+ # Remove all tokens with a probability less than the last token of the top-k
259
+ indices_to_remove = (
260
+ logits < torch.topk(logits, top_k, dim=1)[0][..., -1, None]
261
+ )
262
+ logits[indices_to_remove] = float("-inf")
263
+
264
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
265
+
266
+ cumulative_probs = torch.cumsum(
267
+ F.softmax(sorted_logits, dim=-1), dim=-1
268
+ )
269
+ # Remove tokens with cumulative probability above the threshold
270
+ sorted_indices_to_remove = cumulative_probs > top_p
271
+ # Shift the indices to the right to keep also the first token above the threshold
272
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[
273
+ ..., :-1
274
+ ].clone()
275
+ sorted_indices_to_remove[..., 0] = 0
276
+
277
+ # Replace logits to be removed with -inf in the sorted_logits
278
+ sorted_logits[sorted_indices_to_remove] = float("-inf")
279
+ # Then reverse the sorting process by mapping back sorted_logits to their original position
280
+ logits = torch.gather(sorted_logits, 1, sorted_indices.argsort(-1))
281
+
282
+ # Convert sorted indices back to original vocab indices
283
+ next_tokens = torch.multinomial(F.softmax(logits, -1), 1)
284
+ else:
285
+ next_tokens = torch.argmax(logits, dim=-1, keepdim=True)
286
+
287
+ tokens = torch.cat((tokens, next_tokens), dim=1)
288
+
289
+ return tokens.flatten()
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30ceeaf70221fc1e9e030423fda7b2aad4f93a850d4e05167f569ef23b47dda0
3
+ size 497951283