N8Programs/ProGen2-base-bf16
117
1# coding=utf-82# 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.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# 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.py17 18from typing import Tuple19 20import numpy as np21 22import torch23import torch.utils.checkpoint24from torch import nn25from torch.nn import CrossEntropyLoss26import torch.nn.functional as F27 28from transformers.activations import ACT2FN29from transformers.modeling_outputs import (30 BaseModelOutputWithPast,31 CausalLMOutputWithPast,32)33from transformers.modeling_utils import PreTrainedModel34from transformers.utils import logging35from .configuration_progen import ProGenConfig36 37 38logger = logging.get_logger(__name__)39 40 41def 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 54def 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 60def 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, 364 ),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 71class ProGenAttention(nn.Module):72 def __init__(self, config):73 super().__init__()74 75 max_positions = config.n_positions76 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=False82 )83 self.register_buffer("masked_bias", torch.tensor(-1e9), persistent=False) # approx. -inf84 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_dim89 self.num_attention_heads = config.n_head90 self.head_dim = self.embed_dim // self.num_attention_heads91 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 = None102 if config.rotary_dim is not None:103 self.rotary_dim = config.rotary_dim104 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 x109 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_positions113 """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 buffer134 query_length, key_length = query.size(-2), key.size(-2)135 causal_mask = self.bias[136 :, :, key_length - query_length : key_length, :key_length137 ]138 139 # Keep the attention weights computation in fp32 to avoid overflow issues140 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_attn146 147 # attend only to previous positions148 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_mask154 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_mask161 162 attn_output = attn_weights @ value # (B, n_heads, T, dim_head)163 164 return attn_output, attn_weights165 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 = 8178 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 = 0189 190 if layer_past is not None:191 offset = layer_past[0].shape[-2]192 seq_len += offset193 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 = None225 226 # compute self-attention: softmax((Q @ K.T) / sqrt(dim_head)) @ V227 attn_output, attn_weights = self._attn(228 query, key, value, attention_mask, head_mask229 )230 231 attn_output = self._merge_heads( # (B, T, E) 232 attn_output, self.num_attention_heads, self.head_dim233 )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 245class ProGenMLP(nn.Module):246 def __init__(247 self, intermediate_size, config248 ): # in MLP: intermediate_size= 4 * embed_dim249 super().__init__()250 embed_dim = config.embed_dim251 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_states264 265 266class 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_dim270 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_states284 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 + residual298 299 if use_cache:300 outputs = (hidden_states,) + outputs301 else:302 outputs = (hidden_states,) + outputs[1:]303 304 return outputs # hidden_states, present, (attentions)305 306 307class ProGenPreTrainedModel(PreTrainedModel):308 """309 An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained310 models.311 """312 313 config_class = ProGenConfig314 base_model_prefix = "transformer"315 is_parallelizable = False316 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 initialization324 # cf https://github.com/pytorch/pytorch/pull/5617325 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 337class ProGenModel(ProGenPreTrainedModel):338 def __init__(self, config):339 super().__init__(config)340 self.vocab_size_emb = config.vocab_size_emb341 self.embed_dim = config.embed_dim342 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_head348 )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_attentions367 if output_attentions is not None368 else self.config.output_attentions369 )370 output_hidden_states = (371 output_hidden_states372 if output_hidden_states is not None373 else self.config.output_hidden_states374 )375 use_cache = use_cache if use_cache is not None else self.config.use_cache376 return_dict = (377 return_dict if return_dict is not None else self.config.use_return_dict378 )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.device395 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 = 0404 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 attention425 # 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 for429 # masked positions, this operation will create a tensor which is 0.0 for430 # 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 is432 # effectively the same as removing these entirely.433 attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility434 attention_mask = (1.0 - attention_mask) * -10000.0435 436 # Prepare head mask if needed437 # 1.0 in head_mask indicate we keep the head438 # attention_probs has shape bsz x num_attention_heads x N x N439 # head_mask has shape n_layer x batch x num_attention_heads x N x N440 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_embeds446 447 if token_type_ids is not None:448 token_type_embeds = self.wte(token_type_ids)449 hidden_states = hidden_states + token_type_embeds450 451 hidden_states = self.drop(hidden_states)452 453 output_shape = input_shape + (hidden_states.size(-1),)454 455 presents = () if use_cache else None456 all_self_attentions = () if output_attentions else None457 all_hidden_states = () if output_hidden_states else None458 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 = False469 470 def create_custom_forward(module):471 def custom_forward(*inputs):472 # None for past_key_value473 return module(*inputs, use_cache, output_attentions)474 475 return custom_forward476 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 state507 if output_hidden_states:508 all_hidden_states = all_hidden_states + (hidden_states,)509 510 if not return_dict:511 return tuple(512 v513 for v in [514 hidden_states,515 presents,516 all_hidden_states,517 all_self_attentions,518 ]519 if v is not None520 )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 530class 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 kwargs546 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 generation556 position_ids = attention_mask.long().cumsum(-1) - 1557 position_ids.masked_fill_(attention_mask == 0, 1)558 if past:559 position_ids = position_ids[:, -1].unsqueeze(-1)560 else:561 position_ids = None562 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 set589 ``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to590 ``-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_dict594 )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 and612 # compute loss in fp32 to match with mesh-tf version613 # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179614 lm_logits = self.lm_head(hidden_states).to(torch.float32)615 616 loss = None617 if labels is not None:618 # Shift so that tokens < n predict n619 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 output630 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 @staticmethod640 def _reorder_cache(641 past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor642 ) -> Tuple[Tuple[torch.Tensor]]:643 """644 This function is used to re-order the :obj:`past_key_values` cache if645 :meth:`~transformers.PretrainedModel.beam_search` or :meth:`~transformers.PretrainedModel.beam_sample` is646 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_past652 )653 for layer_past in past654 )655 