BeardedMonster commited on
Commit
2228dd4
1 Parent(s): 1da9b21

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,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/pretrainedmodel",
3
+ "architectures": [
4
+ "GPTJXForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "pretrained_config.GPTJXConfig",
8
+ "AutoModelForCausalLM": "pretrained_model.GPTJXForCausalLM"
9
+ },
10
+ "bias": false,
11
+ "block_size": 1024,
12
+ "dropout": 0.0,
13
+ "model_type": "nanogpt-j",
14
+ "n_embd": 768,
15
+ "n_head": 12,
16
+ "n_layer": 12,
17
+ "torch_dtype": "float32",
18
+ "transformers_version": "4.39.3",
19
+ "vocab_size": 52050
20
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.39.3"
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,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GPTJXForCausalLM(PreTrainedModel):
15
+ config_class = GPTJXConfig
16
+ base_model_prefix = "transformer"
17
+ is_parallelizable = True
18
+ supports_gradient_checkpointing = True
19
+ _no_split_modules = ["BlockJ"]
20
+ # _skip_keys_device_placement = "past_key_values"
21
+ _supports_flash_attn_2 = True
22
+ _tied_weights_keys = ["lm_head.weight"]
23
+
24
+
25
+ def __init__(self, config):
26
+ super().__init__(config)
27
+ assert config.vocab_size is not None
28
+ assert config.block_size is not None
29
+ self.config = config
30
+
31
+ self.transformer = nn.ModuleDict(dict(
32
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
33
+ wpe = nn.Embedding(config.block_size, config.n_embd),
34
+ drop = nn.Dropout(config.dropout),
35
+ h = nn.ModuleList([BlockJ(config) for _ in range(config.n_layer)]),
36
+ ln_f = LayerNorm(config.n_embd, bias=config.bias),
37
+ ))
38
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
39
+ # with weight tying when using torch.compile() some warnings get generated:
40
+ # "UserWarning: functional_call was passed multiple values for tied weights.
41
+ # This behavior is deprecated and will be an error in future versions"
42
+ # not 100% sure what this is, so far seems to be harmless. TODO investigate
43
+ self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
44
+
45
+ # init all weights
46
+ self.apply(self._init_weights)
47
+ # apply special scaled init to the residual projections, per GPT-2 paper
48
+ for pn, p in self.named_parameters():
49
+ if pn.endswith('c_proj.weight'):
50
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
51
+
52
+ # report number of parameters
53
+ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
54
+
55
+ def get_num_params(self, non_embedding=True):
56
+ """
57
+ Return the number of parameters in the model.
58
+ For non-embedding count (default), the position embeddings get subtracted.
59
+ The token embeddings would too, except due to the parameter sharing these
60
+ params are actually used as weights in the final layer, so we include them.
61
+ """
62
+ n_params = sum(p.numel() for p in self.parameters())
63
+ if non_embedding:
64
+ n_params -= self.transformer.wpe.weight.numel()
65
+ return n_params
66
+
67
+
68
+ def get_input_embeddings(self):
69
+ return self.wte
70
+
71
+ def set_input_embeddings(self, new_embeddings):
72
+ self.wte = new_embeddings
73
+
74
+ def forward(self, idx, targets=None, attn_mask= None, output_hidden_states: Optional[bool] = None, **kwargs):
75
+ device = idx.device
76
+ b, t = idx.size()
77
+
78
+ # attn_mask = _prepare_mask_(idx, b, eval)
79
+ # print("attention mask: ", attn_mask)
80
+
81
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
82
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
83
+
84
+ # forward the GPT model itself
85
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
86
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
87
+ x = self.transformer.drop(tok_emb + pos_emb)
88
+ for block in self.transformer.h:
89
+ x = block(x, attn_mask=attn_mask)
90
+ x = self.transformer.ln_f(x)
91
+
92
+ if targets is not None:
93
+ # if we are given some desired targets also calculate the loss
94
+ logits = self.lm_head(x)
95
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
96
+ else:
97
+ # inference-time mini-optimization: only forward the lm_head on the very last position
98
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
99
+ loss = None
100
+
101
+ # return {"logits": logits, "loss": loss}
102
+ return CausalLMOutputWithPast(
103
+ loss=loss,
104
+ logits=logits,
105
+ hidden_states=x if output_hidden_states else None,
106
+ attentions= None,
107
+ )
108
+
109
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
110
+ # Default model inputs
111
+ model_inputs = {"idx": input_ids}
112
+
113
+ # Add attention mask if provided
114
+ if attention_mask is not None:
115
+ model_inputs["attn_mask"] = attention_mask
116
+
117
+ return model_inputs
118
+
119
+
120
+ @torch.no_grad()
121
+ def stream(self, idx, max_new_tokens, temperature=1.0, top_k=None,gen_mode="greedy"):
122
+ """
123
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
124
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
125
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
126
+ """
127
+ for _ in range(max_new_tokens):
128
+ # if the sequence context is growing too long we must crop it at block_size
129
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
130
+ # forward the model to get the logits for the index in the sequence
131
+ logits, _ = self(idx_cond, eval=True)
132
+ # pluck the logits at the final step and scale by desired temperature
133
+ logits = logits[:, -1, :] / temperature
134
+ # optionally crop the logits to only the top k options
135
+ if top_k is not None:
136
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
137
+ logits[logits < v[:, [-1]]] = -float('Inf')
138
+ # apply softmax to convert logits to (normalized) probabilities
139
+ probs = F.softmax(logits, dim=-1)
140
+ # sample from the distribution
141
+ if gen_mode == 'greedy':
142
+ idx_next = torch.argmax(probs, dim=-1).unsqueeze(0)
143
+
144
+ else:
145
+ idx_next = torch.multinomial(probs, num_samples=1)
146
+ # print(idx_next.shape, idx.shape)
147
+ idx = torch.cat((idx, idx_next), dim=1)
148
+ # append sampled index to the running sequence and continue
149
+ yield idx_next
150
+
151
+
152
+ def crop_block_size(self, block_size):
153
+ # model surgery to decrease the block size if necessary
154
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
155
+ # but want to use a smaller block size for some smaller, simpler model
156
+ assert block_size <= self.config.block_size
157
+ self.config.block_size = block_size
158
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
159
+ for block in self.transformer.h:
160
+ if hasattr(block.attn, 'bias'):
161
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
162
+
163
+
164
+ AutoConfig.register("nanogpt-j", GPTJXConfig)
165
+ AutoModel.register(GPTJXConfig,GPTJXForCausalLM)
166
+ AutoModelForCausalLM.register(GPTJXConfig, GPTJXForCausalLM)
167
+
168
+
169
+ if __name__ == '__main__':
170
+ from transformers import AutoTokenizer
171
+
172
+ tokenizer = AutoTokenizer.from_pretrained("BeardedMonster/SabiYarn")
173
+ input_ids = tokenizer("ba wo ni?", return_tensors="pt")["input_ids"]
174
+ targets = input_ids
175
+
176
+ # config = GPTJConfig()
177
+ # config.save_pretrained("gptj-config")
178
+ # new_config = GPTJ.from_pretrained("gptj-config")
179
+ # model = GPTJ(config)
180
+ # state_dict = torch.load('model.pt', map_location="cpu")
181
+ # model.load_state_dict(state_dict)
182
+ model = GPTJXForCausalLM.from_pretrained("/pretrainedmodel")
183
+ # model.save_pretrained("/pretrainedmodel")
184
+ outputs = model(input_ids, targets)
185
+ print(outputs)
186
+ output = model.generate(input_ids, max_new_tokens=100)
187
+ print(tokenizer.decode(output[0]))
188
+ # print(new_config)