BeardedMonster commited on
Commit
8e504d1
·
verified ·
1 Parent(s): dc65a4c

Upload GPTJXForCausalLM

Browse files
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
+ "GPTJXForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "pretrained_config.GPTJXConfig",
7
+ "AutoModelForCausalLM": "pretrained_model.GPTJXForCausalLM"
8
+ },
9
+ "bias": false,
10
+ "block_size": 1024,
11
+ "dropout": 0.0,
12
+ "model_type": "nanogpt-j",
13
+ "n_embd": 768,
14
+ "n_head": 12,
15
+ "n_layer": 12,
16
+ "torch_dtype": "float32",
17
+ "transformers_version": "4.41.2",
18
+ "vocab_size": 52050
19
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.41.2"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:135619ec5be52e21223cd0c9dfec01af7f7f1b4600fd7af22d4d1db313a7a6ee
3
+ size 553275408
pretrained_config.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+ repo_name = "BeardedMonster/SabiYarn-125M"
4
+
5
+ class GPTJXConfig(PretrainedConfig):
6
+ model_type="nanogpt-j"
7
+
8
+
9
+ def __init__(self,
10
+ block_size: int = 1024,
11
+ vocab_size: int = 52050, #50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
12
+ n_layer: int = 12,
13
+ n_head: int = 12,
14
+ n_embd: int = 768,
15
+ dropout: float = 0.0,
16
+ bias: bool = False, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
17
+ **kwargs
18
+ ):
19
+
20
+ self.block_size = block_size
21
+ self.vocab_size = vocab_size
22
+ self.n_layer = n_layer
23
+ self.n_head = n_head
24
+ self.n_embd = n_embd
25
+ self.dropout = dropout
26
+ self.bias = bias
27
+
28
+ super().__init__(**kwargs)
29
+
30
+
pretrained_model.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoConfig, PreTrainedModel, AutoModelForCausalLM
2
+ from typing import List, Optional
3
+ from torch import nn
4
+ # from model import LayerNorm, BlockJ
5
+ from transformers.modeling_outputs import CausalLMOutputWithPast
6
+ import torch
7
+ import math
8
+ from torch.nn import functional as F
9
+ from transformers import AutoConfig, AutoModel
10
+ from .pretrained_config import *
11
+
12
+
13
+
14
+ class LayerNorm(nn.Module):
15
+ """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
16
+
17
+ def __init__(self, ndim, bias):
18
+ super().__init__()
19
+ self.weight = nn.Parameter(torch.ones(ndim))
20
+ self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
21
+
22
+ def forward(self, input):
23
+ return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
24
+
25
+ class CausalSelfAttention(nn.Module):
26
+
27
+ def __init__(self, config):
28
+ super().__init__()
29
+ assert config.n_embd % config.n_head == 0
30
+ # key, query, value projections for all heads, but in a batch
31
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
32
+ # output projection
33
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
34
+ # regularization
35
+ self.attn_dropout = nn.Dropout(config.dropout)
36
+ self.resid_dropout = nn.Dropout(config.dropout)
37
+ self.n_head = config.n_head
38
+ self.n_embd = config.n_embd
39
+ self.dropout = config.dropout
40
+ # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
41
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
42
+ # if not self.flash:
43
+ # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
44
+ # causal mask to ensure that attention is only applied to the left in the input sequence
45
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
46
+ .view(1, 1, config.block_size, config.block_size))
47
+
48
+ def forward(self, x, attn_mask=None):
49
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
50
+
51
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
52
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
53
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
54
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
55
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
56
+
57
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
58
+ if self.flash:
59
+ if attn_mask is not None:
60
+ # efficient attention using Flash Attention CUDA kernels
61
+ attn_mask = attn_mask.to(torch.bool)
62
+ y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0)
63
+ else:
64
+ y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
65
+ else:
66
+ # manual implementation of attention
67
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
68
+ att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
69
+ att = F.softmax(att, dim=-1)
70
+ att = self.attn_dropout(att)
71
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
72
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
73
+
74
+ # output projection
75
+ y = self.resid_dropout(self.c_proj(y))
76
+ return y
77
+
78
+ class MLP(nn.Module):
79
+
80
+ def __init__(self, config):
81
+ super().__init__()
82
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
83
+ self.gelu = nn.GELU()
84
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
85
+ self.dropout = nn.Dropout(config.dropout)
86
+
87
+ def forward(self, x):
88
+ x = self.c_fc(x)
89
+ x = self.gelu(x)
90
+ x = self.c_proj(x)
91
+ x = self.dropout(x)
92
+ return x
93
+
94
+ class BlockJ(nn.Module):
95
+
96
+ def __init__(self, config):
97
+ super().__init__()
98
+ self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
99
+ self.j = LayerNorm(config.n_embd, config.n_embd)
100
+ self.attn = CausalSelfAttention(config)
101
+ self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
102
+ self.mlp = MLP(config)
103
+
104
+ def forward(self, x, attn_mask=None):
105
+ h = x
106
+ x = self.ln_1(x)
107
+ x = h + self.attn(x, attn_mask) + self.j(x)
108
+ x = x + self.mlp(self.ln_2(x))
109
+ return x
110
+
111
+
112
+ class GPTJXForCausalLM(PreTrainedModel):
113
+ config_class = GPTJXConfig
114
+ base_model_prefix = "transformer"
115
+ is_parallelizable = True
116
+ supports_gradient_checkpointing = True
117
+ _no_split_modules = ["BlockJ"]
118
+ # _skip_keys_device_placement = "past_key_values"
119
+ _supports_flash_attn_2 = True
120
+ _tied_weights_keys = ["lm_head.weight"]
121
+
122
+
123
+ def __init__(self, config):
124
+ super().__init__(config)
125
+ assert config.vocab_size is not None
126
+ assert config.block_size is not None
127
+ self.config = config
128
+
129
+ self.transformer = nn.ModuleDict(dict(
130
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
131
+ wpe = nn.Embedding(config.block_size, config.n_embd),
132
+ drop = nn.Dropout(config.dropout),
133
+ h = nn.ModuleList([BlockJ(config) for _ in range(config.n_layer)]),
134
+ ln_f = LayerNorm(config.n_embd, bias=config.bias),
135
+ ))
136
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
137
+ # with weight tying when using torch.compile() some warnings get generated:
138
+ # "UserWarning: functional_call was passed multiple values for tied weights.
139
+ # This behavior is deprecated and will be an error in future versions"
140
+ # not 100% sure what this is, so far seems to be harmless. TODO investigate
141
+ self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
142
+
143
+ # init all weights
144
+ self.apply(self._init_weights)
145
+ # apply special scaled init to the residual projections, per GPT-2 paper
146
+ for pn, p in self.named_parameters():
147
+ if pn.endswith('c_proj.weight'):
148
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
149
+
150
+ # report number of parameters
151
+ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
152
+
153
+ def get_num_params(self, non_embedding=True):
154
+ """
155
+ Return the number of parameters in the model.
156
+ For non-embedding count (default), the position embeddings get subtracted.
157
+ The token embeddings would too, except due to the parameter sharing these
158
+ params are actually used as weights in the final layer, so we include them.
159
+ """
160
+ n_params = sum(p.numel() for p in self.parameters())
161
+ if non_embedding:
162
+ n_params -= self.transformer.wpe.weight.numel()
163
+ return n_params
164
+
165
+
166
+ def get_input_embeddings(self):
167
+ return self.wte
168
+
169
+ def set_input_embeddings(self, new_embeddings):
170
+ self.wte = new_embeddings
171
+
172
+ def forward(self, idx, targets=None, attn_mask= None, output_hidden_states: Optional[bool] = None, **kwargs):
173
+ device = idx.device
174
+ b, t = idx.size()
175
+
176
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
177
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
178
+
179
+ # forward the GPT model itself
180
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
181
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
182
+ x = self.transformer.drop(tok_emb + pos_emb)
183
+ for block in self.transformer.h:
184
+ x = block(x, attn_mask=attn_mask)
185
+ x = self.transformer.ln_f(x)
186
+
187
+ # logits = self.lm_head(x) # logits over the entire sequence, shape (b, t, vocab_size)
188
+ if targets is not None:
189
+ # if we are given some desired targets also calculate the loss
190
+ logits = self.lm_head(x)
191
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
192
+ else:
193
+ # inference-time mini-optimization: only forward the lm_head on the very last position
194
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
195
+ loss = None
196
+
197
+ # if targets is not None:
198
+ # # If targets are provided, compute the loss
199
+ # loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
200
+ # else:
201
+ # # Inference-time: return logits for each timestep
202
+ # loss = None
203
+
204
+ return CausalLMOutputWithPast(
205
+ loss=loss,
206
+ logits=logits,
207
+ hidden_states=x if output_hidden_states else None,
208
+ attentions= None,
209
+ )
210
+
211
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
212
+ # Default model inputs
213
+ model_inputs = {"idx": input_ids}
214
+
215
+ # Add attention mask if provided
216
+ if attention_mask is not None:
217
+ model_inputs["attn_mask"] = attention_mask
218
+
219
+ return model_inputs
220
+
221
+
222
+ def crop_block_size(self, block_size):
223
+ # model surgery to decrease the block size if necessary
224
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
225
+ # but want to use a smaller block size for some smaller, simpler model
226
+ assert block_size <= self.config.block_size
227
+ self.config.block_size = block_size
228
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
229
+ for block in self.transformer.h:
230
+ if hasattr(block.attn, 'bias'):
231
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
232
+
233
+
234
+ AutoConfig.register("nanogpt-j", GPTJXConfig)
235
+ AutoModel.register(GPTJXConfig,GPTJXForCausalLM)
236
+ AutoModelForCausalLM.register(GPTJXConfig, GPTJXForCausalLM)
237
+