hugohrban commited on
Commit
4a87924
1 Parent(s): bfc0518

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