xhyi commited on
Commit
a49dc3e
1 Parent(s): 34a9d32

Upload modeling_codegen.py

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