z-liu commited on
Commit
df80c36
·
verified ·
1 Parent(s): adc35f7

Upload 2 files

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