hugohrban commited on
Commit
3fcef8b
1 Parent(s): e1bcbc5

Upload ProGenForCausalLM

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,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./checkpoints/31979_e5",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "ProGenForCausalLM"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_progen.ProGenConfig",
10
+ "AutoModelForCausalLM": "modeling_progen.ProGenForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "embd_pdrop": 0.0,
14
+ "embed_dim": 1024,
15
+ "eos_token_id": 2,
16
+ "gradient_checkpointing": false,
17
+ "initializer_range": 0.02,
18
+ "layer_norm_epsilon": 1e-05,
19
+ "model_type": "progen",
20
+ "n_embd": 1024,
21
+ "n_head": 16,
22
+ "n_inner": null,
23
+ "n_layer": 12,
24
+ "n_positions": 1024,
25
+ "resid_pdrop": 0.0,
26
+ "rotary_dim": 32,
27
+ "scale_attn_weights": true,
28
+ "summary_activation": null,
29
+ "summary_first_dropout": 0.1,
30
+ "summary_proj_to_labels": true,
31
+ "summary_type": "cls_index",
32
+ "summary_use_proj": true,
33
+ "tokenizer_class": "GPT2Tokenizer",
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.40.0",
36
+ "use_cache": true,
37
+ "vocab_size_emb": 37,
38
+ "vocab_size_lm_head": 32
39
+ }
configuration_progen.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Modified configuration implementation based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/gptj/configuration_gptj.py
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class ProGenConfig(PretrainedConfig):
25
+ model_type = "progen"
26
+
27
+ def __init__(
28
+ self,
29
+ vocab_size_emb=32,
30
+ vocab_size_lm_head=32,
31
+ n_positions=1024,
32
+ embed_dim=1024,
33
+ n_layer=12,
34
+ n_head=16,
35
+ rotary_dim=32,
36
+ n_inner=None,
37
+ activation_function="gelu_new",
38
+ resid_pdrop=0.0,
39
+ embd_pdrop=0.0,
40
+ attn_pdrop=0.0,
41
+ layer_norm_epsilon=1e-5,
42
+ initializer_range=0.02,
43
+ scale_attn_weights=True,
44
+ gradient_checkpointing=False,
45
+ use_cache=True,
46
+ bos_token_id=1,
47
+ eos_token_id=2,
48
+ **kwargs
49
+ ):
50
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
51
+
52
+ self.vocab_size_emb = vocab_size_emb # input vocab size
53
+ self.vocab_size_lm_head = vocab_size_lm_head # output vocab size
54
+ self.n_positions = n_positions # context window size
55
+ self.embed_dim = embed_dim
56
+ self.n_layer = n_layer
57
+ self.n_head = n_head
58
+ self.n_inner = n_inner # inner dimension of the MLP
59
+ self.rotary_dim = rotary_dim
60
+ self.activation_function = activation_function
61
+ self.resid_pdrop = resid_pdrop
62
+ self.embd_pdrop = embd_pdrop
63
+ self.attn_pdrop = attn_pdrop
64
+ self.layer_norm_epsilon = layer_norm_epsilon
65
+ self.initializer_range = initializer_range
66
+ self.gradient_checkpointing = gradient_checkpointing
67
+ self.scale_attn_weights = scale_attn_weights
68
+ self.use_cache = use_cache
69
+
70
+ self.bos_token_id = bos_token_id
71
+ self.eos_token_id = eos_token_id
72
+
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.40.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:249370d76e34f5e61c9a2ad8130ada747f7f99bc8239769f0b24ff516cd2fbb4
3
+ size 617210712
modeling_progen.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License atí
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Modified forward-pass implementation based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/gptj/modeling_gptj.py
17
+
18
+ from typing import Tuple
19
+
20
+ import numpy as np
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+ import torch.nn.functional as F
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import logging
35
+ from .configuration_progen import ProGenConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ def fixed_pos_embedding(x, seq_dim=1, seq_len=None):
42
+ dim = x.shape[-1]
43
+ if seq_len is None:
44
+ seq_len = x.shape[seq_dim]
45
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
46
+ sinusoid_inp = (
47
+ torch.einsum("i , j -> i j", torch.arange(seq_len), inv_freq)
48
+ .to(x.device)
49
+ .float()
50
+ )
51
+ return torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)
52
+
53
+
54
+ def rotate_every_two(x: torch.Tensor):
55
+ x1 = x[:, :, :, ::2]
56
+ x2 = x[:, :, :, 1::2]
57
+ x = torch.stack((-x2, x1), axis=-1)
58
+ return x.flatten(-2)
59
+
60
+ def apply_rotary_pos_emb(x, sincos, offset=0):
61
+ sin, cos = map(
62
+ lambda t: t[None, offset : x.shape[1] + offset, None, :].repeat_interleave(
63
+ 2, 3
64
+ ),
65
+ sincos,
66
+ )
67
+ # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
68
+ return (x * cos) + (rotate_every_two(x) * sin)
69
+
70
+
71
+ class ProGenAttention(nn.Module):
72
+ def __init__(self, config):
73
+ super().__init__()
74
+
75
+ max_positions = config.n_positions
76
+ self.register_buffer(
77
+ "bias",
78
+ torch.tril(
79
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
80
+ ).view(1, 1, max_positions, max_positions),
81
+ )
82
+ self.register_buffer("masked_bias", torch.tensor(-1e9)) # approx. -inf
83
+
84
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
85
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
86
+
87
+ self.embed_dim = config.embed_dim
88
+ self.num_attention_heads = config.n_head
89
+ self.head_dim = self.embed_dim // self.num_attention_heads
90
+ if self.head_dim * self.num_attention_heads != self.embed_dim:
91
+ raise ValueError(
92
+ f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and `num_attention_heads`: {self.num_attention_heads})."
93
+ )
94
+ self.scale_attn = torch.sqrt(
95
+ torch.tensor(self.head_dim, dtype=torch.float32)
96
+ ).to(torch.get_default_dtype())
97
+ self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
98
+
99
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
100
+ self.rotary_dim = None
101
+ if config.rotary_dim is not None:
102
+ self.rotary_dim = config.rotary_dim
103
+
104
+ def _split_heads(self, x: torch.Tensor, n_head, dim_head) -> torch.Tensor:
105
+ x = x.reshape(x.shape[:-2] + (-1,)) # (B, T, 8 * E // 8)
106
+ x = x.reshape(x.shape[:-1] + (n_head, dim_head)) # (B, T, n_heads, dim_head)
107
+ return x
108
+
109
+ def _merge_heads(self, tensor, num_attention_heads, attn_head_size) -> torch.Tensor:
110
+ """
111
+ Merges attn_head_size dim and num_attn_heads dim into n_positions
112
+ """
113
+ if len(tensor.shape) == 5:
114
+ tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
115
+ elif len(tensor.shape) == 4:
116
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
117
+ else:
118
+ raise ValueError(
119
+ f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}"
120
+ )
121
+ new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
122
+ return tensor.view(new_shape)
123
+
124
+ def _attn(
125
+ self,
126
+ query,
127
+ key,
128
+ value,
129
+ attention_mask=None,
130
+ head_mask=None,
131
+ ):
132
+ # compute causal mask from causal mask buffer
133
+ query_length, key_length = query.size(-2), key.size(-2)
134
+ causal_mask = self.bias[
135
+ :, :, key_length - query_length : key_length, :key_length
136
+ ]
137
+
138
+ # Keep the attention weights computation in fp32 to avoid overflow issues
139
+ query = query.to(torch.float32)
140
+ key = key.to(torch.float32)
141
+
142
+ attn_weights = query @ key.transpose(-1, -2) # (B, n_heads, T, T)
143
+
144
+ attn_weights = attn_weights / self.scale_attn
145
+
146
+ # attend only to previous positions
147
+ attn_weights = torch.where(
148
+ causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype)
149
+ )
150
+
151
+ if attention_mask is not None:
152
+ attn_weights = attn_weights + attention_mask
153
+
154
+ attn_weights = F.softmax(attn_weights, dim=-1)
155
+ attn_weights = attn_weights.to(value.dtype)
156
+ attn_weights = self.attn_dropout(attn_weights)
157
+
158
+ if head_mask is not None:
159
+ attn_weights = attn_weights * head_mask
160
+
161
+ attn_output = attn_weights @ value # (B, n_heads, T, dim_head)
162
+
163
+ return attn_output, attn_weights
164
+
165
+ def forward(
166
+ self,
167
+ hidden_states,
168
+ attention_mask=None,
169
+ layer_past=None,
170
+ head_mask=None,
171
+ use_cache=False,
172
+ output_attentions=False,
173
+ ):
174
+ qkv = self.qkv_proj(hidden_states) # (B, T, 3 * E)
175
+
176
+ mp_num = 8
177
+ qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1)) # (B, T, 8, 3 * E // 8)
178
+
179
+ query, value, key = torch.split(qkv_split, self.embed_dim // mp_num, dim=-1) # 3 * (B, T, 8, E // 8)
180
+
181
+ query = self._split_heads(query, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
182
+ key = self._split_heads(key, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
183
+ value = self._split_heads(value, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
184
+ value = value.permute(0, 2, 1, 3)
185
+
186
+ seq_len = key.shape[1]
187
+ offset = 0
188
+
189
+ if layer_past is not None:
190
+ offset = layer_past[0].shape[-2]
191
+ seq_len += offset
192
+
193
+ if self.rotary_dim is not None:
194
+ k_rot = key[:, :, :, : self.rotary_dim]
195
+ k_pass = key[:, :, :, self.rotary_dim :]
196
+
197
+ q_rot = query[:, :, :, : self.rotary_dim]
198
+ q_pass = query[:, :, :, self.rotary_dim :]
199
+
200
+ sincos = fixed_pos_embedding(k_rot, 1, seq_len=seq_len)
201
+ k_rot = apply_rotary_pos_emb(k_rot, sincos, offset=offset)
202
+ q_rot = apply_rotary_pos_emb(q_rot, sincos, offset=offset)
203
+
204
+ key = torch.cat([k_rot, k_pass], dim=-1)
205
+ query = torch.cat([q_rot, q_pass], dim=-1)
206
+ else:
207
+ sincos = fixed_pos_embedding(key, 1, seq_len=seq_len)
208
+ key = apply_rotary_pos_emb(key, sincos, offset=offset)
209
+ query = apply_rotary_pos_emb(query, sincos, offset=offset)
210
+
211
+ key = key.permute(0, 2, 1, 3)
212
+ query = query.permute(0, 2, 1, 3)
213
+
214
+ if layer_past is not None:
215
+ past_key = layer_past[0]
216
+ past_value = layer_past[1]
217
+ key = torch.cat((past_key, key), dim=-2)
218
+ value = torch.cat((past_value, value), dim=-2)
219
+
220
+ if use_cache is True:
221
+ present = (key, value)
222
+ else:
223
+ present = None
224
+
225
+ # compute self-attention: softmax((Q @ K.T) / sqrt(dim_head)) @ V
226
+ attn_output, attn_weights = self._attn(
227
+ query, key, value, attention_mask, head_mask
228
+ )
229
+
230
+ attn_output = self._merge_heads( # (B, T, E)
231
+ attn_output, self.num_attention_heads, self.head_dim
232
+ )
233
+
234
+ attn_output = self.out_proj(attn_output)
235
+ attn_output = self.resid_dropout(attn_output)
236
+
237
+ outputs = (attn_output, present)
238
+ if output_attentions:
239
+ outputs += (attn_weights,)
240
+
241
+ return outputs # a, present, (attentions)
242
+
243
+
244
+ class ProGenMLP(nn.Module):
245
+ def __init__(
246
+ self, intermediate_size, config
247
+ ): # in MLP: intermediate_size= 4 * embed_dim
248
+ super().__init__()
249
+ embed_dim = config.embed_dim
250
+
251
+ self.fc_in = nn.Linear(embed_dim, intermediate_size)
252
+ self.fc_out = nn.Linear(intermediate_size, embed_dim)
253
+
254
+ self.act = ACT2FN[config.activation_function]
255
+ self.dropout = nn.Dropout(config.resid_pdrop)
256
+
257
+ def forward(self, hidden_states):
258
+ hidden_states = self.fc_in(hidden_states)
259
+ hidden_states = self.act(hidden_states)
260
+ hidden_states = self.fc_out(hidden_states)
261
+ hidden_states = self.dropout(hidden_states)
262
+ return hidden_states
263
+
264
+
265
+ class ProGenBlock(nn.Module):
266
+ def __init__(self, config):
267
+ super().__init__()
268
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * config.embed_dim
269
+ self.ln_1 = nn.LayerNorm(config.embed_dim, eps=config.layer_norm_epsilon)
270
+ self.attn = ProGenAttention(config)
271
+ self.mlp = ProGenMLP(inner_dim, config)
272
+
273
+ def forward(
274
+ self,
275
+ hidden_states,
276
+ layer_past=None,
277
+ attention_mask=None,
278
+ head_mask=None,
279
+ use_cache=False,
280
+ output_attentions=False,
281
+ ):
282
+ residual = hidden_states
283
+ hidden_states = self.ln_1(hidden_states)
284
+ attn_outputs = self.attn(
285
+ hidden_states,
286
+ layer_past=layer_past,
287
+ attention_mask=attention_mask,
288
+ head_mask=head_mask,
289
+ use_cache=use_cache,
290
+ output_attentions=output_attentions,
291
+ )
292
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
293
+ outputs = attn_outputs[1:]
294
+
295
+ feed_forward_hidden_states = self.mlp(hidden_states) # (B, T, E)
296
+ hidden_states = attn_output + feed_forward_hidden_states + residual
297
+
298
+ if use_cache:
299
+ outputs = (hidden_states,) + outputs
300
+ else:
301
+ outputs = (hidden_states,) + outputs[1:]
302
+
303
+ return outputs # hidden_states, present, (attentions)
304
+
305
+
306
+ class ProGenPreTrainedModel(PreTrainedModel):
307
+ """
308
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
309
+ models.
310
+ """
311
+
312
+ config_class = ProGenConfig
313
+ base_model_prefix = "transformer"
314
+ is_parallelizable = False
315
+
316
+ def __init__(self, *inputs, **kwargs):
317
+ super().__init__(*inputs, **kwargs)
318
+
319
+ def _init_weights(self, module):
320
+ """Initialize the weights."""
321
+ if isinstance(module, (nn.Linear,)):
322
+ # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
323
+ # cf https://github.com/pytorch/pytorch/pull/5617
324
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
325
+ if module.bias is not None:
326
+ module.bias.data.zero_()
327
+ elif isinstance(module, nn.Embedding):
328
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
329
+ if module.padding_idx is not None:
330
+ module.weight.data[module.padding_idx].zero_()
331
+ elif isinstance(module, nn.LayerNorm):
332
+ module.bias.data.zero_()
333
+ module.weight.data.fill_(1.0)
334
+
335
+
336
+ class ProGenModel(ProGenPreTrainedModel):
337
+ def __init__(self, config):
338
+ super().__init__(config)
339
+ self.vocab_size_emb = config.vocab_size_emb
340
+ self.embed_dim = config.embed_dim
341
+ self.wte = nn.Embedding(config.vocab_size_emb, self.embed_dim)
342
+ self.drop = nn.Dropout(config.embd_pdrop)
343
+ self.h = nn.ModuleList([ProGenBlock(config) for _ in range(config.n_layer)])
344
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
345
+ self.rotary_dim = min(
346
+ config.rotary_dim, config.n_positions // config.n_head
347
+ )
348
+ self.init_weights()
349
+
350
+ def forward(
351
+ self,
352
+ input_ids=None,
353
+ past_key_values=None,
354
+ attention_mask=None,
355
+ token_type_ids=None,
356
+ position_ids=None,
357
+ head_mask=None,
358
+ inputs_embeds=None,
359
+ use_cache=None,
360
+ output_attentions=None,
361
+ output_hidden_states=None,
362
+ return_dict=None,
363
+ ):
364
+ output_attentions = (
365
+ output_attentions
366
+ if output_attentions is not None
367
+ else self.config.output_attentions
368
+ )
369
+ output_hidden_states = (
370
+ output_hidden_states
371
+ if output_hidden_states is not None
372
+ else self.config.output_hidden_states
373
+ )
374
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
375
+ return_dict = (
376
+ return_dict if return_dict is not None else self.config.use_return_dict
377
+ )
378
+
379
+ if input_ids is not None and inputs_embeds is not None:
380
+ raise ValueError(
381
+ "You cannot specify both input_ids and inputs_embeds at the same time"
382
+ )
383
+ elif input_ids is not None:
384
+ input_shape = input_ids.size()
385
+ input_ids = input_ids.view(-1, input_shape[-1])
386
+ batch_size = input_ids.shape[0]
387
+ elif inputs_embeds is not None:
388
+ input_shape = inputs_embeds.size()[:-1]
389
+ batch_size = inputs_embeds.shape[0]
390
+ else:
391
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
392
+
393
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
394
+
395
+ if token_type_ids is not None:
396
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
397
+
398
+ if position_ids is not None:
399
+ position_ids = position_ids.view(-1, input_shape[-1])
400
+
401
+ if past_key_values is None:
402
+ past_length = 0
403
+ past_key_values = tuple([None] * len(self.h))
404
+ else:
405
+ past_length = past_key_values[0][0].size(-2)
406
+
407
+ if position_ids is None:
408
+ position_ids = torch.arange(
409
+ past_length,
410
+ input_shape[-1] + past_length,
411
+ dtype=torch.long,
412
+ device=device,
413
+ )
414
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
415
+
416
+ # Attention mask.
417
+ if attention_mask is not None:
418
+ assert batch_size > 0, "batch_size has to be defined and > 0"
419
+ attention_mask = attention_mask.view(batch_size, -1)
420
+ # We create a 3D attention mask from a 2D tensor mask.
421
+ # Sizes are [batch_size, 1, 1, to_seq_length]
422
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
423
+ # this attention mask is more simple than the triangular masking of causal attention
424
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
425
+ attention_mask = attention_mask[:, None, None, :]
426
+
427
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
428
+ # masked positions, this operation will create a tensor which is 0.0 for
429
+ # positions we want to attend and -10000.0 for masked positions.
430
+ # Since we are adding it to the raw scores before the softmax, this is
431
+ # effectively the same as removing these entirely.
432
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
433
+ attention_mask = (1.0 - attention_mask) * -10000.0
434
+
435
+ # Prepare head mask if needed
436
+ # 1.0 in head_mask indicate we keep the head
437
+ # attention_probs has shape bsz x num_attention_heads x N x N
438
+ # head_mask has shape n_layer x batch x num_attention_heads x N x N
439
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
440
+
441
+ if inputs_embeds is None:
442
+ inputs_embeds = self.wte(input_ids)
443
+
444
+ hidden_states = inputs_embeds
445
+
446
+ if token_type_ids is not None:
447
+ token_type_embeds = self.wte(token_type_ids)
448
+ hidden_states = hidden_states + token_type_embeds
449
+
450
+ hidden_states = self.drop(hidden_states)
451
+
452
+ output_shape = input_shape + (hidden_states.size(-1),)
453
+
454
+ presents = () if use_cache else None
455
+ all_self_attentions = () if output_attentions else None
456
+ all_hidden_states = () if output_hidden_states else None
457
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
458
+ if output_hidden_states:
459
+ all_hidden_states = all_hidden_states + (hidden_states,)
460
+
461
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
462
+ if use_cache:
463
+ logger.warning(
464
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
465
+ "`use_cache=False`..."
466
+ )
467
+ use_cache = False
468
+
469
+ def create_custom_forward(module):
470
+ def custom_forward(*inputs):
471
+ # None for past_key_value
472
+ return module(*inputs, use_cache, output_attentions)
473
+
474
+ return custom_forward
475
+
476
+ outputs = torch.utils.checkpoint.checkpoint(
477
+ create_custom_forward(block),
478
+ hidden_states,
479
+ None,
480
+ attention_mask,
481
+ head_mask[i],
482
+ )
483
+ else:
484
+ outputs = block(
485
+ hidden_states,
486
+ layer_past=layer_past,
487
+ attention_mask=attention_mask,
488
+ head_mask=head_mask[i],
489
+ use_cache=use_cache,
490
+ output_attentions=output_attentions,
491
+ )
492
+
493
+ hidden_states = outputs[0]
494
+ if use_cache is True:
495
+ presents = presents + (outputs[1],)
496
+
497
+ if output_attentions:
498
+ all_self_attentions = all_self_attentions + (
499
+ outputs[2 if use_cache else 1],
500
+ )
501
+
502
+ hidden_states = self.ln_f(hidden_states)
503
+
504
+ hidden_states = hidden_states.view(*output_shape)
505
+ # Add last hidden state
506
+ if output_hidden_states:
507
+ all_hidden_states = all_hidden_states + (hidden_states,)
508
+
509
+ if not return_dict:
510
+ return tuple(
511
+ v
512
+ for v in [
513
+ hidden_states,
514
+ presents,
515
+ all_hidden_states,
516
+ all_self_attentions,
517
+ ]
518
+ if v is not None
519
+ )
520
+
521
+ return BaseModelOutputWithPast(
522
+ last_hidden_state=hidden_states,
523
+ past_key_values=presents,
524
+ hidden_states=all_hidden_states,
525
+ attentions=all_self_attentions,
526
+ )
527
+
528
+
529
+ class ProGenForCausalLM(ProGenPreTrainedModel):
530
+ _keys_to_ignore_on_load_missing = [
531
+ r"h\.\d+\.attn\.masked_bias",
532
+ r"h\.\d+\.attn\.bias",
533
+ r"lm_head\.weight",
534
+ ]
535
+
536
+ def __init__(self, config):
537
+ super().__init__(config)
538
+ self.transformer = ProGenModel(config)
539
+ self.lm_head = nn.Linear(config.embed_dim, config.vocab_size_lm_head)
540
+ self.init_weights()
541
+
542
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
543
+ token_type_ids = kwargs.get("token_type_ids", None)
544
+ # only last token for inputs_ids if past is defined in kwargs
545
+ if past:
546
+ input_ids = input_ids[:, -1].unsqueeze(-1)
547
+ if token_type_ids is not None:
548
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
549
+
550
+ attention_mask = kwargs.get("attention_mask", None)
551
+ position_ids = kwargs.get("position_ids", None)
552
+
553
+ if attention_mask is not None and position_ids is None:
554
+ # create position_ids on the fly for batch generation
555
+ position_ids = attention_mask.long().cumsum(-1) - 1
556
+ position_ids.masked_fill_(attention_mask == 0, 1)
557
+ if past:
558
+ position_ids = position_ids[:, -1].unsqueeze(-1)
559
+ else:
560
+ position_ids = None
561
+ return {
562
+ "input_ids": input_ids,
563
+ "past_key_values": past,
564
+ "use_cache": kwargs.get("use_cache"),
565
+ "position_ids": position_ids,
566
+ "attention_mask": attention_mask,
567
+ "token_type_ids": token_type_ids,
568
+ }
569
+
570
+ def forward(
571
+ self,
572
+ input_ids=None,
573
+ past_key_values=None,
574
+ attention_mask=None,
575
+ token_type_ids=None,
576
+ position_ids=None,
577
+ head_mask=None,
578
+ inputs_embeds=None,
579
+ labels=None,
580
+ use_cache=None,
581
+ output_attentions=None,
582
+ output_hidden_states=None,
583
+ return_dict=None,
584
+ ):
585
+ r"""
586
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
587
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
588
+ ``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to
589
+ ``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
590
+ """
591
+ return_dict = (
592
+ return_dict if return_dict is not None else self.config.use_return_dict
593
+ )
594
+
595
+ transformer_outputs = self.transformer(
596
+ input_ids,
597
+ past_key_values=past_key_values,
598
+ attention_mask=attention_mask,
599
+ token_type_ids=token_type_ids,
600
+ position_ids=position_ids,
601
+ head_mask=head_mask,
602
+ inputs_embeds=inputs_embeds,
603
+ use_cache=use_cache,
604
+ output_attentions=output_attentions,
605
+ output_hidden_states=output_hidden_states,
606
+ return_dict=return_dict,
607
+ )
608
+ hidden_states = transformer_outputs[0]
609
+
610
+ # make sure sampling in fp16 works correctly and
611
+ # compute loss in fp32 to match with mesh-tf version
612
+ # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
613
+ lm_logits = self.lm_head(hidden_states).to(torch.float32)
614
+
615
+ loss = None
616
+ if labels is not None:
617
+ # Shift so that tokens < n predict n
618
+ shift_logits = lm_logits[..., :-1, :].contiguous()
619
+ shift_labels = labels[..., 1:].contiguous()
620
+ loss_fct = CrossEntropyLoss()
621
+ loss = loss_fct(
622
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
623
+ )
624
+ loss = loss.to(hidden_states.dtype)
625
+
626
+ if not return_dict:
627
+ output = (lm_logits,) + transformer_outputs[1:]
628
+ return ((loss,) + output) if loss is not None else output
629
+
630
+ return CausalLMOutputWithPast(
631
+ loss=loss,
632
+ logits=lm_logits,
633
+ past_key_values=transformer_outputs.past_key_values,
634
+ hidden_states=transformer_outputs.hidden_states,
635
+ attentions=transformer_outputs.attentions,
636
+ )
637
+
638
+ @staticmethod
639
+ def _reorder_cache(
640
+ past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
641
+ ) -> Tuple[Tuple[torch.Tensor]]:
642
+ """
643
+ This function is used to re-order the :obj:`past_key_values` cache if
644
+ :meth:`~transformers.PretrainedModel.beam_search` or :meth:`~transformers.PretrainedModel.beam_sample` is
645
+ called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
646
+ """
647
+ return tuple(
648
+ tuple(
649
+ past_state.index_select(0, beam_idx.to(past_state.device))
650
+ for past_state in layer_past
651
+ )
652
+ for layer_past in past
653
+ )