import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)




def    lowerCAmelCase_  (		lowercase:				Tuple		)     ->					List[Any]:







 '''simple docstring'''
 _UpperCamelCase:  Union[str, Any]    						=			torch.exp(lowercase		)
 _UpperCamelCase:  Union[str, Any]    						=			torch.sum(lowercase	,       dim=1		)  # sum of exp(x_i)
 _UpperCamelCase:  Dict    						=			torch.sum(x * exp_x	,       dim=1		)  # sum of x_i * exp(x_i)
 return torch.log(lowercase		) - B / A




class 			__magic_name__	(		nn.Module     ):





   """simple docstring"""




   def __init__(						self       :	Union[str, Any]		,	_lowercase       :	List[str]				):



    """simple docstring"""



    super().__init__()
    _UpperCamelCase:  Optional[int]    						=			config.output_attentions
    _UpperCamelCase:  Any    						=			config.output_hidden_states
    _UpperCamelCase:  Dict    						=			nn.ModuleList([BertLayer(_lowercase				) for _ in range(config.num_hidden_layers				)]				)
    _UpperCamelCase:  Any    						=			nn.ModuleList([BertHighway(_lowercase				) for _ in range(config.num_hidden_layers				)]				)

    _UpperCamelCase:  Optional[Any]    						=			[-1 for _ in range(config.num_hidden_layers				)]



   def 	lowerCAmelCase    (						self       :	List[str]		,	_lowercase       :	int				):



    """simple docstring"""



    if (type(_lowercase				) is float) or (type(_lowercase				) is int):
     for i in range(len(self.early_exit_entropy				)				):
      _UpperCamelCase:  Optional[Any]    						=			x
    else:
     _UpperCamelCase:  List[str]    						=			x



   def 	lowerCAmelCase    (						self       :	Tuple		,	_lowercase       :	Any				):



    """simple docstring"""



    _UpperCamelCase:  Any    						=			pooler.state_dict()
    for highway in self.highway:
     for name, param in highway.pooler.state_dict().items():
      param.copy_(loaded_model[name]				)



   def 	lowerCAmelCase    (						self       :	List[str]		,	_lowercase       :	List[str]		,	_lowercase       :	int=None		,	_lowercase       :	List[Any]=None		,	_lowercase       :	Tuple=None		,	_lowercase       :	List[Any]=None		,	):



    """simple docstring"""



    _UpperCamelCase:  Optional[int]    						=			()
    _UpperCamelCase:  List[str]    						=			()
    _UpperCamelCase:  List[str]    						=			()
    for i, layer_module in enumerate(self.layer				):
     if self.output_hidden_states:
      _UpperCamelCase:  Tuple    						=			all_hidden_states + (hidden_states,)

     _UpperCamelCase:  Any    						=			layer_module(
         _lowercase		,	_lowercase		,	head_mask[i]		,	_lowercase		,	_lowercase				)
     _UpperCamelCase:  int    						=			layer_outputs[0]

     if self.output_attentions:
      _UpperCamelCase:  int    						=			all_attentions + (layer_outputs[1],)

     _UpperCamelCase:  Any    						=			(hidden_states,)
     if self.output_hidden_states:
      _UpperCamelCase:  Tuple    						=			current_outputs + (all_hidden_states,)
     if self.output_attentions:
      _UpperCamelCase:  Union[str, Any]    						=			current_outputs + (all_attentions,)

     _UpperCamelCase:  Dict    						=			self.highway[i](_lowercase				)
     # logits, pooled_output

     if not self.training:
      _UpperCamelCase:  int    						=			highway_exit[0]
      _UpperCamelCase:  Optional[Any]    						=			entropy(_lowercase				)
      _UpperCamelCase:  Dict    						=			highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
      _UpperCamelCase:  int    						=			all_highway_exits + (highway_exit,)

      if highway_entropy < self.early_exit_entropy[i]:
       _UpperCamelCase:  List[str]    						=			(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
       raise HighwayException(_lowercase		,	i + 1				)
     else:
      _UpperCamelCase:  Tuple    						=			all_highway_exits + (highway_exit,)

        # Add last layer
    if self.output_hidden_states:
     _UpperCamelCase:  Union[str, Any]    						=			all_hidden_states + (hidden_states,)

    _UpperCamelCase:  Dict    						=			(hidden_states,)
    if self.output_hidden_states:
     _UpperCamelCase:  Optional[Any]    						=			outputs + (all_hidden_states,)
    if self.output_attentions:
     _UpperCamelCase:  Dict    						=			outputs + (all_attentions,)

    _UpperCamelCase:  Optional[int]    						=			outputs + (all_highway_exits,)
    return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits




@add_start_docstrings(
    '''The Bert Model transformer with early exiting (DeeBERT). '''   ,						__a   ,						)
class 			__magic_name__	(		__a     ):





   """simple docstring"""




   def __init__(						self       :	Optional[Any]		,	_lowercase       :	Union[str, Any]				):



    """simple docstring"""



    super().__init__(_lowercase				)
    _UpperCamelCase:  Optional[int]    						=			config

    _UpperCamelCase:  Union[str, Any]    						=			BertEmbeddings(_lowercase				)
    _UpperCamelCase:  Dict    						=			DeeBertEncoder(_lowercase				)
    _UpperCamelCase:  Optional[int]    						=			BertPooler(_lowercase				)

    self.init_weights()



   def 	lowerCAmelCase    (						self       :	Optional[Any]				):



    """simple docstring"""



    self.encoder.init_highway_pooler(self.pooler				)



   def 	lowerCAmelCase    (						self       :	Any				):



    """simple docstring"""



    return self.embeddings.word_embeddings



   def 	lowerCAmelCase    (						self       :	Tuple		,	_lowercase       :	Dict				):



    """simple docstring"""



    _UpperCamelCase:  Union[str, Any]    						=			value



   def 	lowerCAmelCase    (						self       :	Optional[Any]		,	_lowercase       :	Dict				):



    """simple docstring"""



    for layer, heads in heads_to_prune.items():
     self.encoder.layer[layer].attention.prune_heads(_lowercase				)



   @add_start_docstrings_to_model_forward(_lowercase				)
   def 	lowerCAmelCase    (						self       :	Any		,	_lowercase       :	int=None		,	_lowercase       :	Tuple=None		,	_lowercase       :	List[str]=None		,	_lowercase       :	Union[str, Any]=None		,	_lowercase       :	Tuple=None		,	_lowercase       :	str=None		,	_lowercase       :	Optional[Any]=None		,	_lowercase       :	Dict=None		,	):



    """simple docstring"""



    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:
     _UpperCamelCase:  List[Any]    						=			input_ids.size()
    elif inputs_embeds is not None:
     _UpperCamelCase:  Optional[Any]    						=			inputs_embeds.size()[:-1]
    else:
     raise ValueError('''You have to specify either input_ids or inputs_embeds'''				)

    _UpperCamelCase:  List[str]    						=			input_ids.device if input_ids is not None else inputs_embeds.device

    if attention_mask is None:
     _UpperCamelCase:  int    						=			torch.ones(_lowercase		,	device=_lowercase				)
    if encoder_attention_mask is None:
     _UpperCamelCase:  Optional[int]    						=			torch.ones(_lowercase		,	device=_lowercase				)
    if token_type_ids is None:
     _UpperCamelCase:  Optional[Any]    						=			torch.zeros(_lowercase		,	dtype=torch.long		,	device=_lowercase				)

    # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
    # ourselves in which case we just need to make it broadcastable to all heads.
    _UpperCamelCase:  torch.Tensor    						=			self.get_extended_attention_mask(_lowercase		,	_lowercase		,	_lowercase				)

    # If a 2D ou 3D attention mask is provided for the cross-attention
    # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
    if encoder_attention_mask.dim() == 3:
     _UpperCamelCase:  List[Any]    						=			encoder_attention_mask[:, None, :, :]
    if encoder_attention_mask.dim() == 2:
     _UpperCamelCase:  int    						=			encoder_attention_mask[:, None, None, :]

    _UpperCamelCase:  List[str]    						=			encoder_extended_attention_mask.to(
        dtype=next(self.parameters()				).dtype				)  # fp16 compatibility
    _UpperCamelCase:  Optional[Any]    						=			(1.0 - encoder_extended_attention_mask) * -10000.0

    # Prepare head mask if needed
    # 1.0 in head_mask indicate we keep the head
    # attention_probs has shape bsz x n_heads x N x N
    # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
    # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
    _UpperCamelCase:  Union[str, Any]    						=			self.get_head_mask(_lowercase		,	self.config.num_hidden_layers				)

    _UpperCamelCase:  List[Any]    						=			self.embeddings(
        input_ids=_lowercase		,	position_ids=_lowercase		,	token_type_ids=_lowercase		,	inputs_embeds=_lowercase				)
    _UpperCamelCase:  Optional[Any]    						=			self.encoder(
        _lowercase		,	attention_mask=_lowercase		,	head_mask=_lowercase		,	encoder_hidden_states=_lowercase		,	encoder_attention_mask=_lowercase		,	)
    _UpperCamelCase:  Dict    						=			encoder_outputs[0]
    _UpperCamelCase:  int    						=			self.pooler(_lowercase				)

    _UpperCamelCase:  Optional[int]    						=			(
        sequence_output,
        pooled_output,
    ) + encoder_outputs[
        1:
    ]  # add hidden_states and attentions if they are here
    return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits




class 			__magic_name__	(		__a     ):





   """simple docstring"""




   def __init__(						self       :	Any		,	_lowercase       :	str		,	_lowercase       :	Dict				):



    """simple docstring"""



    _UpperCamelCase:  int    						=			message
    _UpperCamelCase:  Tuple    						=			exit_layer  # start from 1!




class 			__magic_name__	(		nn.Module     ):





   """simple docstring"""




   def __init__(						self       :	Optional[int]		,	_lowercase       :	Union[str, Any]				):



    """simple docstring"""



    super().__init__()
    _UpperCamelCase:  List[str]    						=			BertPooler(_lowercase				)
    _UpperCamelCase:  List[str]    						=			nn.Dropout(config.hidden_dropout_prob				)
    _UpperCamelCase:  Optional[Any]    						=			nn.Linear(config.hidden_size		,	config.num_labels				)



   def 	lowerCAmelCase    (						self       :	Any		,	_lowercase       :	int				):



    """simple docstring"""



    _UpperCamelCase:  int    						=			encoder_outputs[0]
    _UpperCamelCase:  List[Any]    						=			self.pooler(_lowercase				)
    # "return" pooler_output

    # BertModel
    _UpperCamelCase:  Union[str, Any]    						=			(pooler_input, pooler_output) + encoder_outputs[1:]
    # "return" bmodel_output

    # Dropout and classification
    _UpperCamelCase:  Optional[int]    						=			bmodel_output[1]

    _UpperCamelCase:  Dict    						=			self.dropout(_lowercase				)
    _UpperCamelCase:  int    						=			self.classifier(_lowercase				)

    return logits, pooled_output




@add_start_docstrings(
    '''Bert Model (with early exiting - DeeBERT) with a classifier on top,
    also takes care of multi-layer training. '''   ,						__a   ,						)
class 			__magic_name__	(		__a     ):





   """simple docstring"""




   def __init__(						self       :	Any		,	_lowercase       :	str				):



    """simple docstring"""



    super().__init__(_lowercase				)
    _UpperCamelCase:  Optional[int]    						=			config.num_labels
    _UpperCamelCase:  List[Any]    						=			config.num_hidden_layers

    _UpperCamelCase:  str    						=			DeeBertModel(_lowercase				)
    _UpperCamelCase:  List[str]    						=			nn.Dropout(config.hidden_dropout_prob				)
    _UpperCamelCase:  str    						=			nn.Linear(config.hidden_size		,	self.config.num_labels				)

    self.init_weights()



   @add_start_docstrings_to_model_forward(_lowercase				)
   def 	lowerCAmelCase    (						self       :	Any		,	_lowercase       :	List[str]=None		,	_lowercase       :	List[str]=None		,	_lowercase       :	List[Any]=None		,	_lowercase       :	int=None		,	_lowercase       :	Any=None		,	_lowercase       :	Tuple=None		,	_lowercase       :	Optional[int]=None		,	_lowercase       :	Optional[int]=-1		,	_lowercase       :	Optional[int]=False		,	):



    """simple docstring"""



    _UpperCamelCase:  Dict    						=			self.num_layers
    try:
     _UpperCamelCase:  int    						=			self.bert(
         _lowercase		,	attention_mask=_lowercase		,	token_type_ids=_lowercase		,	position_ids=_lowercase		,	head_mask=_lowercase		,	inputs_embeds=_lowercase		,	)
     # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

     _UpperCamelCase:  List[Any]    						=			outputs[1]

     _UpperCamelCase:  Any    						=			self.dropout(_lowercase				)
     _UpperCamelCase:  Tuple    						=			self.classifier(_lowercase				)
     _UpperCamelCase:  Any    						=			(logits,) + outputs[2:]  # add hidden states and attention if they are here
    except HighwayException as e:
     _UpperCamelCase:  str    						=			e.message
     _UpperCamelCase:  Optional[Any]    						=			e.exit_layer
     _UpperCamelCase:  Optional[Any]    						=			outputs[0]

    if not self.training:
     _UpperCamelCase:  Dict    						=			entropy(_lowercase				)
     _UpperCamelCase:  List[str]    						=			[]
     _UpperCamelCase:  Tuple    						=			[]
    if labels is not None:
     if self.num_labels == 1:
      #  We are doing regression
      _UpperCamelCase:  Optional[Any]    						=			MSELoss()
      _UpperCamelCase:  Dict    						=			loss_fct(logits.view(-1				)		,	labels.view(-1				)				)
     else:
      _UpperCamelCase:  Dict    						=			CrossEntropyLoss()
      _UpperCamelCase:  int    						=			loss_fct(logits.view(-1		,	self.num_labels				)		,	labels.view(-1				)				)

     # work with highway exits
     _UpperCamelCase:  List[str]    						=			[]
     for highway_exit in outputs[-1]:
      _UpperCamelCase:  Dict    						=			highway_exit[0]
      if not self.training:
       highway_logits_all.append(_lowercase				)
       highway_entropy.append(highway_exit[2]				)
      if self.num_labels == 1:
       #  We are doing regression
       _UpperCamelCase:  Any    						=			MSELoss()
       _UpperCamelCase:  Tuple    						=			loss_fct(highway_logits.view(-1				)		,	labels.view(-1				)				)
      else:
       _UpperCamelCase:  List[str]    						=			CrossEntropyLoss()
       _UpperCamelCase:  Union[str, Any]    						=			loss_fct(highway_logits.view(-1		,	self.num_labels				)		,	labels.view(-1				)				)
      highway_losses.append(_lowercase				)

     if train_highway:
      _UpperCamelCase:  Any    						=			(sum(highway_losses[:-1]				),) + outputs
      # exclude the final highway, of course
     else:
      _UpperCamelCase:  Any    						=			(loss,) + outputs
    if not self.training:
     _UpperCamelCase:  Optional[int]    						=			outputs + ((original_entropy, highway_entropy), exit_layer)
     if output_layer >= 0:
      _UpperCamelCase:  Tuple    						=			(
          (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
      )  # use the highway of the last layer

    return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)
import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
UpperCAmelCase_           =				data_utils.TransfoXLTokenizer
UpperCAmelCase_           =				data_utils.TransfoXLCorpus
UpperCAmelCase_           =				data_utils
UpperCAmelCase_           =				data_utils




def    lowerCAmelCase_  (		lowercase:				Tuple	,       lowercase:				Union[str, Any]	,       lowercase:				Any	,       lowercase:				List[Any]		)     ->					List[Any]:







 '''simple docstring'''
 if transfo_xl_dataset_file:
  # Convert a pre-processed corpus (see original TensorFlow repo)
  with open(lowercase	,       '''rb'''		) as fp:
   _UpperCamelCase:  Optional[int]    						=			pickle.load(lowercase	,       encoding='''latin1'''		)
  # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
  _UpperCamelCase:  Tuple    						=			pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file''']
  print(F"""Save vocabulary to {pytorch_vocab_dump_path}"""		)
  _UpperCamelCase:  List[str]    						=			corpus.vocab.__dict__
  torch.save(lowercase	,       lowercase		)

  _UpperCamelCase:  str    						=			corpus.__dict__
  corpus_dict_no_vocab.pop('''vocab'''	,       lowercase		)
  _UpperCamelCase:  str    						=			pytorch_dump_folder_path + '''/''' + CORPUS_NAME
  print(F"""Save dataset to {pytorch_dataset_dump_path}"""		)
  torch.save(lowercase	,       lowercase		)

 if tf_checkpoint_path:
  # Convert a pre-trained TensorFlow model
  _UpperCamelCase:  Optional[Any]    						=			os.path.abspath(lowercase		)
  _UpperCamelCase:  List[str]    						=			os.path.abspath(lowercase		)

  print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}."""		)
  # Initialise PyTorch model
  if transfo_xl_config_file == "":
   _UpperCamelCase:  Tuple    						=			TransfoXLConfig()
  else:
   _UpperCamelCase:  Union[str, Any]    						=			TransfoXLConfig.from_json_file(lowercase		)
  print(F"""Building PyTorch model from configuration: {config}"""		)
  _UpperCamelCase:  Optional[int]    						=			TransfoXLLMHeadModel(lowercase		)

  _UpperCamelCase:  int    						=			load_tf_weights_in_transfo_xl(lowercase	,       lowercase	,       lowercase		)
  # Save pytorch-model
  _UpperCamelCase:  List[str]    						=			os.path.join(lowercase	,       lowercase		)
  _UpperCamelCase:  Union[str, Any]    						=			os.path.join(lowercase	,       lowercase		)
  print(F"""Save PyTorch model to {os.path.abspath(lowercase		)}"""		)
  torch.save(model.state_dict()	,       lowercase		)
  print(F"""Save configuration file to {os.path.abspath(lowercase		)}"""		)
  with open(lowercase	,       '''w'''	,       encoding='''utf-8'''		) as f:
   f.write(config.to_json_string()		)


if __name__ == "__main__":
  UpperCAmelCase_           =				argparse.ArgumentParser()
  parser.add_argument(
      '''--pytorch_dump_folder_path''',
      default=None,
      type=str,
      required=True,
      help='''Path to the folder to store the PyTorch model or dataset/vocab.''',
  )
  parser.add_argument(
      '''--tf_checkpoint_path''',
      default='''''',
      type=str,
      help='''An optional path to a TensorFlow checkpoint path to be converted.''',
  )
  parser.add_argument(
      '''--transfo_xl_config_file''',
      default='''''',
      type=str,
      help=(
          '''An optional config json file corresponding to the pre-trained BERT model. \n'''
          '''This specifies the model architecture.'''
      ),
  )
  parser.add_argument(
      '''--transfo_xl_dataset_file''',
      default='''''',
      type=str,
      help='''An optional dataset file to be converted in a vocabulary.''',
  )
  UpperCAmelCase_           =				parser.parse_args()
  convert_transfo_xl_checkpoint_to_pytorch(
      args.tf_checkpoint_path,
      args.transfo_xl_config_file,
      args.pytorch_dump_folder_path,
      args.transfo_xl_dataset_file,
  )