

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     __lowercase					(   _A	)   ->  Dict:
      SCREAMING_SNAKE_CASE       :					str        =      torch.exp(__UpperCamelCase	)
      SCREAMING_SNAKE_CASE       :					Any        =      torch.sum(__UpperCamelCase  ,			dim=1	)  # sum of exp(x_i)
      SCREAMING_SNAKE_CASE       :					int        =      torch.sum(x * exp_x  ,			dim=1	)  # sum of x_i * exp(x_i)
      return torch.log(__UpperCamelCase	) - B / A







class 				a__				(      nn.Module				):







  """simple docstring"""




  def __init__(	self			:       str , UpperCAmelCase__			:       Optional[Any]						)    ->Tuple:
        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      config.output_attentions
        SCREAMING_SNAKE_CASE       :					Tuple        =      config.output_hidden_states
        SCREAMING_SNAKE_CASE       :					Optional[Any]        =      nn.ModuleList([BertLayer(A_						) for _ in range(config.num_hidden_layers						)]						)
        SCREAMING_SNAKE_CASE       :					int        =      nn.ModuleList([BertHighway(A_						) for _ in range(config.num_hidden_layers						)]						)

        SCREAMING_SNAKE_CASE       :					str        =      [-1 for _ in range(config.num_hidden_layers						)]


  def        _lowercase					(	self			:       Optional[Any] , UpperCAmelCase__			:       Dict						)    ->int:
        """simple docstring"""







        if (type(A_						) is float) or (type(A_						) is int):
              for i in range(len(self.early_exit_entropy						)						):
                    SCREAMING_SNAKE_CASE       :					Optional[Any]        =      x
        else:
              SCREAMING_SNAKE_CASE       :					Dict        =      x


  def        _lowercase					(	self			:       Tuple , UpperCAmelCase__			:       int						)    ->List[Any]:
        """simple docstring"""







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




  def        _lowercase					(	self			:       int , UpperCAmelCase__			:       Tuple , UpperCAmelCase__			:       Tuple=None , UpperCAmelCase__			:       int=None , UpperCAmelCase__			:       str=None , UpperCAmelCase__			:       Dict=None , )    ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       :					Optional[int]        =      ()
        SCREAMING_SNAKE_CASE       :					str        =      ()
        SCREAMING_SNAKE_CASE       :					Optional[Any]        =      ()
        for i, layer_module in enumerate(self.layer						):
              if self.output_hidden_states:
                    SCREAMING_SNAKE_CASE       :					Dict        =      all_hidden_states + (hidden_states,)

              SCREAMING_SNAKE_CASE       :					Dict        =      layer_module(
                  A_ , A_ , head_mask[i] , A_ , A_						)
              SCREAMING_SNAKE_CASE       :					str        =      layer_outputs[0]

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

              SCREAMING_SNAKE_CASE       :					List[Any]        =      (hidden_states,)
              if self.output_hidden_states:
                    SCREAMING_SNAKE_CASE       :					Tuple        =      current_outputs + (all_hidden_states,)
              if self.output_attentions:
                    SCREAMING_SNAKE_CASE       :					Any        =      current_outputs + (all_attentions,)

              SCREAMING_SNAKE_CASE       :					str        =      self.highway[i](A_						)
              # logits, pooled_output

              if not self.training:
                    SCREAMING_SNAKE_CASE       :					List[str]        =      highway_exit[0]
                    SCREAMING_SNAKE_CASE       :					str        =      entropy(A_						)
                    SCREAMING_SNAKE_CASE       :					str        =      highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                    SCREAMING_SNAKE_CASE       :					str        =      all_highway_exits + (highway_exit,)

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

        # Add last layer
        if self.output_hidden_states:
              SCREAMING_SNAKE_CASE       :					Dict        =      all_hidden_states + (hidden_states,)

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

        SCREAMING_SNAKE_CASE       :					Dict        =      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). """		,	UpperCamelCase_		,	)
class 				a__				(      UpperCamelCase_				):







  """simple docstring"""




  def __init__(	self			:       str , UpperCAmelCase__			:       Optional[int]						)    ->Tuple:
        """simple docstring"""







        super().__init__(A_						)
        SCREAMING_SNAKE_CASE       :					List[str]        =      config

        SCREAMING_SNAKE_CASE       :					List[Any]        =      BertEmbeddings(A_						)
        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      DeeBertEncoder(A_						)
        SCREAMING_SNAKE_CASE       :					Any        =      BertPooler(A_						)

        self.init_weights()


  def        _lowercase					(	self			:       List[Any]						)    ->Dict:
        """simple docstring"""







        self.encoder.init_highway_pooler(self.pooler						)


  def        _lowercase					(	self			:       Union[str, Any]						)    ->Dict:
        """simple docstring"""







        return self.embeddings.word_embeddings


  def        _lowercase					(	self			:       List[str] , UpperCAmelCase__			:       List[Any]						)    ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       :					Dict        =      value


  def        _lowercase					(	self			:       Tuple , UpperCAmelCase__			:       int						)    ->Optional[Any]:
        """simple docstring"""







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




  @add_start_docstrings_to_model_forward(A_						)
  def        _lowercase					(	self			:       Tuple , UpperCAmelCase__			:       Union[str, Any]=None , UpperCAmelCase__			:       str=None , UpperCAmelCase__			:       str=None , UpperCAmelCase__			:       str=None , UpperCAmelCase__			:       List[str]=None , UpperCAmelCase__			:       Optional[int]=None , UpperCAmelCase__			:       Union[str, Any]=None , UpperCAmelCase__			:       Any=None , )    ->List[Any]:
        """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:
              SCREAMING_SNAKE_CASE       :					List[Any]        =      input_ids.size()
        elif inputs_embeds is not None:
              SCREAMING_SNAKE_CASE       :					Dict        =      inputs_embeds.size()[:-1]
        else:
              raise ValueError("""You have to specify either input_ids or inputs_embeds"""						)

        SCREAMING_SNAKE_CASE       :					Any        =      input_ids.device if input_ids is not None else inputs_embeds.device

        if attention_mask is None:
              SCREAMING_SNAKE_CASE       :					Tuple        =      torch.ones(A_ , device=A_						)
        if encoder_attention_mask is None:
              SCREAMING_SNAKE_CASE       :					str        =      torch.ones(A_ , device=A_						)
        if token_type_ids is None:
              SCREAMING_SNAKE_CASE       :					str        =      torch.zeros(A_ , dtype=torch.long , device=A_						)

        # 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.
        SCREAMING_SNAKE_CASE       :					torch.Tensor        =      self.get_extended_attention_mask(A_ , A_ , A_						)

        # 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:
              SCREAMING_SNAKE_CASE       :					List[str]        =      encoder_attention_mask[:, None, :, :]
        if encoder_attention_mask.dim() == 2:
              SCREAMING_SNAKE_CASE       :					Dict        =      encoder_attention_mask[:, None, None, :]

        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      encoder_extended_attention_mask.to(
            dtype=next(self.parameters()						).dtype						)  # fp16 compatibility
        SCREAMING_SNAKE_CASE       :					str        =      (1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.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]
        SCREAMING_SNAKE_CASE       :					int        =      self.get_head_mask(A_ , self.config.num_hidden_layers						)

        SCREAMING_SNAKE_CASE       :					str        =      self.embeddings(
            input_ids=A_ , position_ids=A_ , token_type_ids=A_ , inputs_embeds=A_						)
        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      self.encoder(
            A_ , attention_mask=A_ , head_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , )
        SCREAMING_SNAKE_CASE       :					int        =      encoder_outputs[0]
        SCREAMING_SNAKE_CASE       :					Dict        =      self.pooler(A_						)

        SCREAMING_SNAKE_CASE       :					Tuple        =      (
            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 				a__				(      UpperCamelCase_				):







  """simple docstring"""




  def __init__(	self			:       List[Any] , UpperCAmelCase__			:       Optional[int] , UpperCAmelCase__			:       Optional[int]						)    ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       :					Tuple        =      message
        SCREAMING_SNAKE_CASE       :					List[str]        =      exit_layer  # start from 1!







class 				a__				(      nn.Module				):







  """simple docstring"""




  def __init__(	self			:       List[str] , UpperCAmelCase__			:       Any						)    ->List[Any]:
        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE       :					int        =      BertPooler(A_						)
        SCREAMING_SNAKE_CASE       :					Any        =      nn.Dropout(config.hidden_dropout_prob						)
        SCREAMING_SNAKE_CASE       :					str        =      nn.Linear(config.hidden_size , config.num_labels						)




  def        _lowercase					(	self			:       str , UpperCAmelCase__			:       str						)    ->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       :					Optional[Any]        =      encoder_outputs[0]
        SCREAMING_SNAKE_CASE       :					str        =      self.pooler(A_						)
        # "return" pooler_output

        # BertModel
        SCREAMING_SNAKE_CASE       :					Optional[int]        =      (pooler_input, pooler_output) + encoder_outputs[1:]
        # "return" bmodel_output

        # Dropout and classification
        SCREAMING_SNAKE_CASE       :					int        =      bmodel_output[1]

        SCREAMING_SNAKE_CASE       :					Tuple        =      self.dropout(A_						)
        SCREAMING_SNAKE_CASE       :					Optional[Any]        =      self.classifier(A_						)

        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. """		,	UpperCamelCase_		,	)
class 				a__				(      UpperCamelCase_				):







  """simple docstring"""




  def __init__(	self			:       Dict , UpperCAmelCase__			:       str						)    ->List[str]:
        """simple docstring"""







        super().__init__(A_						)
        SCREAMING_SNAKE_CASE       :					Tuple        =      config.num_labels
        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      config.num_hidden_layers

        SCREAMING_SNAKE_CASE       :					int        =      DeeBertModel(A_						)
        SCREAMING_SNAKE_CASE       :					List[Any]        =      nn.Dropout(config.hidden_dropout_prob						)
        SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      nn.Linear(config.hidden_size , self.config.num_labels						)

        self.init_weights()




  @add_start_docstrings_to_model_forward(A_						)
  def        _lowercase					(	self			:       Union[str, Any] , UpperCAmelCase__			:       List[str]=None , UpperCAmelCase__			:       Any=None , UpperCAmelCase__			:       Any=None , UpperCAmelCase__			:       List[Any]=None , UpperCAmelCase__			:       Tuple=None , UpperCAmelCase__			:       List[Any]=None , UpperCAmelCase__			:       str=None , UpperCAmelCase__			:       str=-1 , UpperCAmelCase__			:       List[Any]=False , )    ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       :					Any        =      self.num_layers
        try:
              SCREAMING_SNAKE_CASE       :					str        =      self.bert(
                  A_ , attention_mask=A_ , token_type_ids=A_ , position_ids=A_ , head_mask=A_ , inputs_embeds=A_ , )
              # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

              SCREAMING_SNAKE_CASE       :					Union[str, Any]        =      outputs[1]

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

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

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

              if train_highway:
                    SCREAMING_SNAKE_CASE       :					List[Any]        =      (sum(highway_losses[:-1]						),) + outputs
                    # exclude the final highway, of course
              else:
                    SCREAMING_SNAKE_CASE       :					int        =      (loss,) + outputs
        if not self.training:
              SCREAMING_SNAKE_CASE       :					Tuple        =      outputs + ((original_entropy, highway_entropy), exit_layer)
              if output_layer >= 0:
                    SCREAMING_SNAKE_CASE       :					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 re

import packaging.version


A__  :  Dict								=					'''examples/'''
A__  :  Any								=					{
    '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''),
    '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
A__  :  Any								=					{
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
A__  :  Any								=					'''README.md'''


def 			UpperCamelCase(  __UpperCamelCase							:		int     ,__UpperCamelCase							:		List[Any]     ,__UpperCamelCase							:		List[Any] ):
		with open(__UpperCamelCase     ,'''r'''     ,encoding='''utf-8'''     ,newline='''\n''' ) as f:
				lowerCAmelCase_			:     Tuple									= f.read()
		lowerCAmelCase_					,  lowerCAmelCase_			:     Dict									= REPLACE_PATTERNS[pattern]
		lowerCAmelCase_			:     Tuple									= replace.replace('''VERSION'''     ,__UpperCamelCase )
		lowerCAmelCase_			:     Optional[int]									= re_pattern.sub(__UpperCamelCase     ,__UpperCamelCase )
		with open(__UpperCamelCase     ,'''w'''     ,encoding='''utf-8'''     ,newline='''\n''' ) as f:
				f.write(__UpperCamelCase )


def 			UpperCamelCase(  __UpperCamelCase							:		Union[str, Any] ):
		for folder, directories, fnames in os.walk(__UpperCamelCase ):
				# Removing some of the folders with non-actively maintained examples from the walk
				if "research_projects" in directories:
						directories.remove('''research_projects''' )
				if "legacy" in directories:
						directories.remove('''legacy''' )
				for fname in fnames:
						if fname.endswith('''.py''' ):
								update_version_in_file(os.path.join(__UpperCamelCase     ,__UpperCamelCase )     ,__UpperCamelCase     ,pattern='''examples''' )


def 			UpperCamelCase(  __UpperCamelCase							:		int     ,__UpperCamelCase							:		List[Any]=False ):
		for pattern, fname in REPLACE_FILES.items():
				update_version_in_file(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase )
		if not patch:
				update_version_in_examples(__UpperCamelCase )


def 			UpperCamelCase(  ):
		lowerCAmelCase_			:     List[str]									= '''🤗 Transformers currently provides the following architectures'''
		lowerCAmelCase_			:     List[Any]									= '''1. Want to contribute a new model?'''
		with open(__UpperCamelCase     ,'''r'''     ,encoding='''utf-8'''     ,newline='''\n''' ) as f:
				lowerCAmelCase_			:     Union[str, Any]									= f.readlines()

		# Find the start of the list.
		lowerCAmelCase_			:     int									= 0
		while not lines[start_index].startswith(_start_prompt ):
				start_index += 1
		start_index += 1

		lowerCAmelCase_			:     str									= start_index
		# Update the lines in the model list.
		while not lines[index].startswith(_end_prompt ):
				if lines[index].startswith('''1.''' ):
						lowerCAmelCase_			:     int									= lines[index].replace(
						    '''https://huggingface.co/docs/transformers/main/model_doc'''     ,'''https://huggingface.co/docs/transformers/model_doc'''     ,)
				index += 1

		with open(__UpperCamelCase     ,'''w'''     ,encoding='''utf-8'''     ,newline='''\n''' ) as f:
				f.writelines(__UpperCamelCase )


def 			UpperCamelCase(  ):
		with open(REPLACE_FILES['''init''']     ,'''r''' ) as f:
				lowerCAmelCase_			:     Optional[Any]									= f.read()
		lowerCAmelCase_			:     Dict									= REPLACE_PATTERNS['''init'''][0].search(__UpperCamelCase ).groups()[0]
		return packaging.version.parse(__UpperCamelCase )


def 			UpperCamelCase(  __UpperCamelCase							:		Dict=False ):
		lowerCAmelCase_			:     Union[str, Any]									= get_version()
		if patch and default_version.is_devrelease:
				raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' )
		if default_version.is_devrelease:
				lowerCAmelCase_			:     List[str]									= default_version.base_version
		elif patch:
				lowerCAmelCase_			:     int									= f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
		else:
				lowerCAmelCase_			:     int									= f"""{default_version.major}.{default_version.minor + 1}.0"""

		# Now let's ask nicely if that's the right one.
		lowerCAmelCase_			:     Optional[Any]									= input(f"""Which version are you releasing? [{default_version}]""" )
		if len(__UpperCamelCase ) == 0:
				lowerCAmelCase_			:     List[str]									= default_version

		print(f"""Updating version to {version}.""" )
		global_version_update(__UpperCamelCase     ,patch=__UpperCamelCase )
		if not patch:
				print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' )
				clean_main_ref_in_model_list()


def 			UpperCamelCase(  ):
		lowerCAmelCase_			:     Any									= get_version()
		lowerCAmelCase_			:     int									= f"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
		lowerCAmelCase_			:     Optional[Any]									= current_version.base_version

		# Check with the user we got that right.
		lowerCAmelCase_			:     Optional[Any]									= input(f"""Which version are we developing now? [{dev_version}]""" )
		if len(__UpperCamelCase ) == 0:
				lowerCAmelCase_			:     int									= dev_version

		print(f"""Updating version to {version}.""" )
		global_version_update(__UpperCamelCase )
		print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' )
		clean_main_ref_in_model_list()


if __name__ == "__main__":
						A__  :  Dict								=					argparse.ArgumentParser()
						parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
						parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
						A__  :  Optional[int]								=					parser.parse_args()
						if not args.post_release:
												pre_release_work(patch=args.patch)
						elif args.patch:
												print('''Nothing to do after a patch :-)''')
						else:
												post_release_work()





