text: """PyTorch OpenAI GPT-2 model.
     Copied from HugginFace, but with some modifications.
  """
  
  import logging
  import math
  import os
  
  import torch
  import torch.nn as nn
  import torch.nn.functional as F
  from torch.nn import CrossEntropyLoss
  
  # pylint:disable=no-member
  
  logger = logging.getLogger(__name__)
  
  
  def gelu_new(x):
      """ Implementation of the gelu activation function currently in Google Bert repo (identical to OpenAI GPT).
          Also see https://arxiv.org/abs/1606.08415
      """
      return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
  
  
  class Conv1D(nn.Module):
      def __init__(self, nf, nx):
          """ Conv1D layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2)
              Basically works like a Linear layer but the weights are transposed
          """
          super().__init__()
          self.nf = nf
          w = torch.empty(nx, nf)
          nn.init.normal_(w, std=0.02)
          self.weight = nn.Parameter(w)
          self.bias = nn.Parameter(torch.zeros(nf))
  
      def forward(self, x):
          size_out = x.size()[:-1] + (self.nf, )
          x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
          x = x.view(*size_out)
          return x
  
  
  class Attention(nn.Module):
      def __init__(self, nx, n_ctx, config, scale=False):
          super().__init__()
          self.output_attentions = config.output_attentions
  
          n_state = nx  # in Attention: n_state=768 (nx=n_embd)
          # [switch nx => n_state from Block to Attention to keep identical to TF implem]
          assert n_state % config.n_head == 0
  
          self.n_head = config.n_head
          self.split_size = n_state
          self.scale = scale
  
          self.c_attn = Conv1D(n_state * 3, nx)
          self.c_proj = Conv1D(n_state, nx)
          self.attn_dropout = nn.Dropout(config.attn_pdrop)
          self.resid_dropout = nn.Dropout(config.resid_pdrop)
  
      def _attn(self, q, k, v, attention_mask):
          w = torch.matmul(q, k)
          if self.scale:
              # scaled by the input sequence length
              w = w / math.sqrt(v.size(-1))
  
          # fast masking attention
          w.masked_fill_(~attention_mask, -1.0e4)
          w = F.softmax(w, dim=-1)
          w = self.attn_dropout(w)
  
          outputs = [torch.matmul(w, v)]
          if self.output_attentions:
              outputs.append(w)
  
          return outputs
  
      def merge_heads(self, x):
          x = x.permute(0, 2, 1, 3).contiguous()
          new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1), )
          return x.view(*new_x_shape)  # in Tensorflow implem: fct merge_states
  
      def split_heads(self, x, k=False):
          new_x_shape = x.size()[:-1] + (self.n_head, x.size(-1) // self.n_head)
          x = x.view(*new_x_shape)  # in Tensorflow implem: fct split_states
          if k:
              return x.permute(0, 2, 3, 1)  # (batch, head, head_features, seq_length)
          else:
              return x.permute(0, 2, 1, 3)  # (batch, head, seq_length, head_features)
  
      def forward(self, x, layer_past, attention_mask):
          x = self.c_attn(x)
          query, key, value = x.split(self.split_size, dim=2)
          query = self.split_heads(query)
          key = self.split_heads(key, k=True)
          value = self.split_heads(value)
          if layer_past is not None:
              past_key, past_value = layer_past[0].transpose(-2, -1), layer_past[1]  # transpose back cf below
              key = torch.cat((past_key, key), dim=-1)
              value = torch.cat((past_value, value), dim=-2)
          present = torch.stack((key.transpose(-2, -1), value))  # transpose to have same shapes for stacking
  
          attn_outputs = self._attn(query, key, value, attention_mask)
          a = attn_outputs[0]
  
          a = self.merge_heads(a)
          a = self.c_proj(a)
          a = self.resid_dropout(a)
  
          outputs = [a, present] + attn_outputs[1:]
          return outputs  # a, present, (attentions)
  
  
  class MLP(nn.Module):
      def __init__(self, n_state, config):  # in MLP: n_state=3072 (4 * n_embd)
          super().__init__()
          nx = config.n_embd
          self.c_fc = Conv1D(n_state, nx)
          self.c_proj = Conv1D(nx, n_state)
          self.act = gelu_new
          self.dropout = nn.Dropout(config.resid_pdrop)
  
      def forward(self, x):
          h = self.act(self.c_fc(x))
          h2 = self.c_proj(h)
          return self.dropout(h2)
  
  
  class Block(nn.Module):
      def __init__(self, n_ctx, config, scale=False):
          super().__init__()
          nx = config.n_embd
          self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
          self.attn = Attention(nx, n_ctx, config, scale)
          self.ln_2 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
          self.mlp = MLP(4 * nx, config)
  
      def forward(self, x, layer_past, attention_mask):
          output_attn = self.attn(self.ln_1(x), layer_past=layer_past, attention_mask=attention_mask)
          a = output_attn[0]  # output_attn: a, present, (attentions)
  
          x = x + a
          m = self.mlp(self.ln_2(x))
          x = x + m
  
          outputs = [x] + output_attn[1:]
          return outputs  # x, present, (attentions)
  
  
  class GPT2Model(nn.Module):
      def __init__(self, config):
          super().__init__()
          self.config = config
          self.output_hidden_states = config.output_hidden_states
          self.output_attentions = config.output_attentions
          self.output_past = config.output_past
  
          self.wte = nn.Embedding(config.vocab_size, config.n_embd)
          self.wpe = nn.Embedding(config.n_positions, config.n_embd)
          self.drop = nn.Dropout(config.embd_pdrop)
          self.h = nn.ModuleList([Block(config.n_ctx, config, scale=True) for _ in range(config.n_layer)])
          self.ln_f = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
  
          self.init_weights()
  
      def forward(
          self,
          input_ids=None,
          past=None,
          attention_mask=None,
          position_ids=None,
          token_type_ids=None,
          inputs_embeds=None,
      ):
          r"""
      Return:
          :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.GPT2Config`) and inputs:
          last_hidden_state (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`):
              Sequence of hidden-states at the last layer of the model.
          past (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers` with each tensor of shape :obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`):
              Contains pre-computed hidden-states (key and values in the attention blocks).
              Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
              should not be passed as input ids as they have already been computed.
          hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
              Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
              of shape :obj:`(batch_size, sequence_length, hidden_size)`.
  
              Hidden-states of the model at the output of each layer plus the initial embedding outputs.
          attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
              Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
              :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
  
              Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
              heads.
  
      Examples::
  
          from transformers import GPT2Tokenizer, GPT2Model
          import torch
  
          tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
          model = GPT2Model.from_pretrained('gpt2')
          input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
          outputs = model(input_ids)
          last_hidden_states = outputs[0]  # The last hidden-state is the first element of the output tuple
  
          """
          if input_ids is not None and inputs_embeds is not None:
              raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
          elif input_ids is not None:
              input_shape = input_ids.size()
              input_ids = input_ids.view(-1, input_shape[-1])
          elif inputs_embeds is not None:
              input_shape = inputs_embeds.size()[:-1]
          else:
              raise ValueError("You have to specify either input_ids or inputs_embeds")
  
          if position_ids is not None:
              position_ids = position_ids.view(-1, input_shape[-1])
  
          if past is None:
              past_length = 0
              past = [None] * len(self.h)
          else:
              past_length = past[0][0].size(-2)
  
          if position_ids is None:
              device = input_ids.device if input_ids is not None else inputs_embeds.device
              position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
              position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
  
          # Attention mask.
  
          if attention_mask is None:
              attention_mask = input_ids != self.config.pad_token_id
  
          attention_mask = attention_mask.view(input_ids.shape[0], 1, 1, attention_mask.shape[1]).repeat(
              1, self.config.n_head, attention_mask.shape[1], 1
          )
          attention_mask = attention_mask & attention_mask.permute(0, 1, 3, 2)
          # only keep the lower triangle for language model
          attention_mask = torch.tril(attention_mask)
          attention_mask = attention_mask[:, :, -input_ids.shape[1]:, :]
  
          if inputs_embeds is None:
              inputs_embeds = self.wte(input_ids)
  
          position_embeds = self.wpe(position_ids)
  
          if token_type_ids is not None:
              token_type_embeds = self.wte(token_type_ids)
          else:
              token_type_embeds = 0
  
          hidden_states = inputs_embeds + position_embeds + token_type_embeds
          hidden_states = self.drop(hidden_states)
  
          output_shape = input_shape + (hidden_states.size(-1), )
  
          presents = ()
          all_attentions = []
          all_hidden_states = ()
          for _, (block, layer_past) in enumerate(zip(self.h, past)):
              if self.output_hidden_states:
                  all_hidden_states = all_hidden_states + (hidden_states.view(*output_shape), )
  
              outputs = block(hidden_states, layer_past=layer_past, attention_mask=attention_mask)
  
              hidden_states, present = outputs[:2]
              if self.output_past:
                  presents = presents + (present, )
  
              if self.output_attentions:
                  all_attentions.append(outputs[2])
  
          hidden_states = self.ln_f(hidden_states)
  
          hidden_states = hidden_states.view(*output_shape)
          # Add last hidden state
          if self.output_hidden_states:
              all_hidden_states = all_hidden_states + (hidden_states, )
  
          outputs = (hidden_states, )
          if self.output_past:
              outputs = outputs + (presents, )
          if self.output_hidden_states:
              outputs = outputs + (all_hidden_states, )
          if self.output_attentions:
              # let the number of heads free (-1) so we can extract attention even after head pruning
              attention_output_shape = input_shape[:-1] + (-1, ) + all_attentions[0].shape[-2:]
              all_attentions = tuple(t.view(*attention_output_shape) for t in all_attentions)
              outputs = outputs + (all_attentions, )
          return outputs  # last hidden state, (presents), (all hidden_states), (attentions)
  
      def init_weights(self):
          """ Initialize and prunes weights if needed. """
          # Initialize weights
          self.apply(self._init_weights)
  
      def _init_weights(self, module):
          """ Initialize the weights.
          """
          if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
              # Slightly different from the TF version which uses truncated_normal for initialization
              # cf https://github.com/pytorch/pytorch/pull/5617
              module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
              if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
                  module.bias.data.zero_()
          elif isinstance(module, nn.LayerNorm):
              module.bias.data.zero_()
              module.weight.data.fill_(1.0)
  
  
  class GPT2LMHeadModel(nn.Module):
      def __init__(self, config):
          super().__init__()
          self.config = config
          self.transformer = GPT2Model(config)
          # self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
  
          self.init_weights()
  
      def forward(
          self,
          input_ids=None,
          past=None,
          attention_mask=None,
          token_type_ids=None,
          position_ids=None,
          inputs_embeds=None,
          labels=None,
      ):
          r"""
          labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
              Labels for language modeling.
              Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
              Indices are selected in ``[-100, 0, ..., config.vocab_size]``
              All labels set to ``-100`` are ignored (masked), the loss is only
              computed for labels in ``[0, ..., config.vocab_size]``
  
      Return:
          :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.GPT2Config`) and inputs:
          loss (:obj:`torch.FloatTensor` of shape `(1,)`, `optional`, returned when ``labels`` is provided)
              Language modeling loss.
          prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
              Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
          past (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers` with each tensor of shape :obj:`(2, batch_size, num_heads, sequence_length, embed_size_per_head)`):
              Contains pre-computed hidden-states (key and values in the attention blocks).
              Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
              should not be passed as input ids as they have already been computed.
          hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``):
              Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
              of shape :obj:`(batch_size, sequence_length, hidden_size)`.
  
              Hidden-states of the model at the output of each layer plus the initial embedding outputs.
          attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``):
              Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape
              :obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
  
              Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
              heads.
  
      Examples::
  
          import torch
          from transformers import GPT2Tokenizer, GPT2LMHeadModel
  
          tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
          model = GPT2LMHeadModel.from_pretrained('gpt2')
  
          input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)  # Batch size 1
          outputs = model(input_ids, labels=input_ids)
          loss, logits = outputs[:2]
  
          """
          transformer_outputs = self.transformer(
              input_ids,
              past=past,
              attention_mask=attention_mask,
              token_type_ids=token_type_ids,
              position_ids=position_ids,
              inputs_embeds=inputs_embeds,
          )
          hidden_states = transformer_outputs[0]
  
          lm_logits = F.linear(hidden_states, self.transformer.wte.weight)
          outputs = (lm_logits, ) + transformer_outputs[1:]
  
          return outputs  # lm_logits, (presents), (all hidden_states), (attentions)
  
      def init_weights(self):
          """ Initialize and prunes weights if needed. """
          # Initialize weights
          self.apply(self._init_weights)
  
      def _init_weights(self, module):
          """ Initialize the weights.
          """
          if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):
              # Slightly different from the TF version which uses truncated_normal for initialization
              # cf https://github.com/pytorch/pytorch/pull/5617
              module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
              if isinstance(module, (nn.Linear, Conv1D)) and module.bias is not None:
                  module.bias.data.zero_()
          elif isinstance(module, nn.LayerNorm):
              module.bias.data.zero_()
              module.weight.data.fill_(1.0)