'''simple docstring'''




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 (							UpperCamelCase__				)	->    int:
    __lowerCamelCase		=  torch.exp(UpperCamelCase__				)
    __lowerCamelCase		=  torch.sum(UpperCamelCase__				,  dim=1				)  # sum of exp(x_i)
    __lowerCamelCase		=  torch.sum(x * exp_x				,  dim=1				)  # sum of x_i * exp(x_i)
    return torch.log(UpperCamelCase__				) - B / A




class     a__      (   nn.Module ):






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





         """simple docstring"""



         super().__init__()
         __lowerCamelCase		=  config.output_attentions
         __lowerCamelCase		=  config.output_hidden_states
         __lowerCamelCase		=  nn.ModuleList([BertLayer(a    ) for _ in range(config.num_hidden_layers    )]    )
         __lowerCamelCase		=  nn.ModuleList([BertHighway(a    ) for _ in range(config.num_hidden_layers    )]    )

         __lowerCamelCase		=  [-1 for _ in range(config.num_hidden_layers    )]






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[Any]  ,				a		:		str    ):





         """simple docstring"""



         if (type(a    ) is float) or (type(a    ) is int):
             for i in range(len(self.early_exit_entropy    )    ):
                 __lowerCamelCase		=  x
         else:
             __lowerCamelCase		=  x






     def    SCREAMING_SNAKE_CASE__   ( self		:		Tuple  ,				a		:		Tuple    ):





         """simple docstring"""



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






     def    SCREAMING_SNAKE_CASE__   ( self		:		Union[str, Any]  ,				a		:		Optional[int]  ,				a		:		Tuple=None  ,				a		:		Optional[Any]=None  ,				a		:		str=None  ,				a		:		str=None  ,				):





         """simple docstring"""



         __lowerCamelCase		=  ()
         __lowerCamelCase		=  ()
         __lowerCamelCase		=  ()
         for i, layer_module in enumerate(self.layer    ):
             if self.output_hidden_states:
                 __lowerCamelCase		=  all_hidden_states + (hidden_states,)

             __lowerCamelCase		=  layer_module(
                 a  ,				a  ,				head_mask[i]  ,				a  ,				a    )
             __lowerCamelCase		=  layer_outputs[0]

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

             __lowerCamelCase		=  (hidden_states,)
             if self.output_hidden_states:
                 __lowerCamelCase		=  current_outputs + (all_hidden_states,)
             if self.output_attentions:
                 __lowerCamelCase		=  current_outputs + (all_attentions,)

             __lowerCamelCase		=  self.highway[i](a    )
             # logits, pooled_output

             if not self.training:
                 __lowerCamelCase		=  highway_exit[0]
                 __lowerCamelCase		=  entropy(a    )
                 __lowerCamelCase		=  highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                 __lowerCamelCase		=  all_highway_exits + (highway_exit,)

                 if highway_entropy < self.early_exit_entropy[i]:
                     __lowerCamelCase		=  (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                     raise HighwayException(a  ,				i + 1    )
             else:
                 __lowerCamelCase		=  all_highway_exits + (highway_exit,)

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

         __lowerCamelCase		=  (hidden_states,)
         if self.output_hidden_states:
             __lowerCamelCase		=  outputs + (all_hidden_states,)
         if self.output_attentions:
             __lowerCamelCase		=  outputs + (all_attentions,)

         __lowerCamelCase		=  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__ ):






     def __init__( self		:		List[Any]  ,				a		:		Optional[Any]    ):





         """simple docstring"""



         super().__init__(a    )
         __lowerCamelCase		=  config

         __lowerCamelCase		=  BertEmbeddings(a    )
         __lowerCamelCase		=  DeeBertEncoder(a    )
         __lowerCamelCase		=  BertPooler(a    )

         self.init_weights()






     def    SCREAMING_SNAKE_CASE__   ( self		:		int    ):





         """simple docstring"""



         self.encoder.init_highway_pooler(self.pooler    )






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[Any]    ):





         """simple docstring"""



         return self.embeddings.word_embeddings






     def    SCREAMING_SNAKE_CASE__   ( self		:		List[Any]  ,				a		:		Optional[Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  value






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[int]  ,				a		:		Dict    ):





         """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    SCREAMING_SNAKE_CASE__   ( self		:		int  ,				a		:		Optional[Any]=None  ,				a		:		Union[str, Any]=None  ,				a		:		Optional[int]=None  ,				a		:		Optional[int]=None  ,				a		:		Any=None  ,				a		:		Optional[Any]=None  ,				a		:		int=None  ,				a		:		Optional[int]=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:
             __lowerCamelCase		=  input_ids.size()
         elif inputs_embeds is not None:
             __lowerCamelCase		=  inputs_embeds.size()[:-1]
         else:
             raise ValueError('''You have to specify either input_ids or inputs_embeds'''    )

         __lowerCamelCase		=  input_ids.device if input_ids is not None else inputs_embeds.device

         if attention_mask is None:
             __lowerCamelCase		=  torch.ones(a  ,				device=a    )
         if encoder_attention_mask is None:
             __lowerCamelCase		=  torch.ones(a  ,				device=a    )
         if token_type_ids is None:
             __lowerCamelCase		=  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.
         __lowerCamelCase		=  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:
             __lowerCamelCase		=  encoder_attention_mask[:, None, :, :]
         if encoder_attention_mask.dim() == 2:
             __lowerCamelCase		=  encoder_attention_mask[:, None, None, :]

         __lowerCamelCase		=  encoder_extended_attention_mask.to(
             dtype=next(self.parameters()    ).dtype    )  # fp16 compatibility
         __lowerCamelCase		=  (1.0 - encoder_extended_attention_mask) * -1_00_00.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]
         __lowerCamelCase		=  self.get_head_mask(a  ,				self.config.num_hidden_layers    )

         __lowerCamelCase		=  self.embeddings(
             input_ids=a  ,				position_ids=a  ,				token_type_ids=a  ,				inputs_embeds=a    )
         __lowerCamelCase		=  self.encoder(
             a  ,				attention_mask=a  ,				head_mask=a  ,				encoder_hidden_states=a  ,				encoder_attention_mask=a  ,				)
         __lowerCamelCase		=  encoder_outputs[0]
         __lowerCamelCase		=  self.pooler(a    )

         __lowerCamelCase		=  (
             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__ ):






     def __init__( self		:		str  ,				a		:		Dict  ,				a		:		List[Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  message
         __lowerCamelCase		=  exit_layer  # start from 1!




class     a__      (   nn.Module ):






     def __init__( self		:		Any  ,				a		:		List[Any]    ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase		=  BertPooler(a    )
         __lowerCamelCase		=  nn.Dropout(config.hidden_dropout_prob    )
         __lowerCamelCase		=  nn.Linear(config.hidden_size  ,				config.num_labels    )






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[int]  ,				a		:		int    ):





         """simple docstring"""



         __lowerCamelCase		=  encoder_outputs[0]
         __lowerCamelCase		=  self.pooler(a    )
         # "return" pooler_output

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

         # Dropout and classification
         __lowerCamelCase		=  bmodel_output[1]

         __lowerCamelCase		=  self.dropout(a    )
         __lowerCamelCase		=  self.classifier(a    )

         return logits, pooled_output




@add_start_docstrings(
    "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n    also takes care of multi-layer training. "							,   UpperCAmelCase__							,   )
class     a__      (   UpperCAmelCase__ ):






     def __init__( self		:		Optional[Any]  ,				a		:		Tuple    ):





         """simple docstring"""



         super().__init__(a    )
         __lowerCamelCase		=  config.num_labels
         __lowerCamelCase		=  config.num_hidden_layers

         __lowerCamelCase		=  DeeBertModel(a    )
         __lowerCamelCase		=  nn.Dropout(config.hidden_dropout_prob    )
         __lowerCamelCase		=  nn.Linear(config.hidden_size  ,				self.config.num_labels    )

         self.init_weights()






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





         """simple docstring"""



         __lowerCamelCase		=  self.num_layers
         try:
             __lowerCamelCase		=  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

             __lowerCamelCase		=  outputs[1]

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

         if not self.training:
             __lowerCamelCase		=  entropy(a    )
             __lowerCamelCase		=  []
             __lowerCamelCase		=  []
         if labels is not None:
             if self.num_labels == 1:
                 #  We are doing regression
                 __lowerCamelCase		=  MSELoss()
                 __lowerCamelCase		=  loss_fct(logits.view(-1    )  ,				labels.view(-1    )    )
             else:
                 __lowerCamelCase		=  CrossEntropyLoss()
                 __lowerCamelCase		=  loss_fct(logits.view(-1  ,				self.num_labels    )  ,				labels.view(-1    )    )

             # work with highway exits
             __lowerCamelCase		=  []
             for highway_exit in outputs[-1]:
                 __lowerCamelCase		=  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
                     __lowerCamelCase		=  MSELoss()
                     __lowerCamelCase		=  loss_fct(highway_logits.view(-1    )  ,				labels.view(-1    )    )
                 else:
                     __lowerCamelCase		=  CrossEntropyLoss()
                     __lowerCamelCase		=  loss_fct(highway_logits.view(-1  ,				self.num_labels    )  ,				labels.view(-1    )    )
                 highway_losses.append(a    )

             if train_highway:
                 __lowerCamelCase		=  (sum(highway_losses[:-1]    ),) + outputs
                 # exclude the final highway, of course
             else:
                 __lowerCamelCase		=  (loss,) + outputs
         if not self.training:
             __lowerCamelCase		=  outputs + ((original_entropy, highway_entropy), exit_layer)
             if output_layer >= 0:
                 __lowerCamelCase		=  (
                     (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 doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


lowerCamelCase											=       logging.getLogger()




@unittest.skip('Temporarily disable the doc tests.'     )
@require_torch
@require_tf
@slow
class A  (   unittest.TestCase     ):






      def        lowerCamelCase       (					self						:     Dict			,   lowercase_						:     Path			,   lowercase_						:     Union[str, None] = None			,   lowercase_						:     Union[List[str], None] = None			,   lowercase_						:     Union[str, List[str], None] = None			,   lowercase_						:     bool = True			,   )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=[file for file in os.listdir(lowercase_ ) if os.path.isfile(os.path.join(lowercase_			,   lowercase_ ) )]

             if identifier is not None:
                    _lowerCamelCase       :		Any		=[file for file in files if identifier in file]

             if n_identifier is not None:
                    if isinstance(lowercase_			,   lowercase_ ):
                           for n_ in n_identifier:
                                  _lowerCamelCase       :		Any		=[file for file in files if n_ not in file]
                    else:
                           _lowerCamelCase       :		List[Any]		=[file for file in files if n_identifier not in file]

             _lowerCamelCase       :		List[Any]		=ignore_files or []
             ignore_files.append('__init__.py' )
             _lowerCamelCase       :		List[Any]		=[file for file in files if file not in ignore_files]

             for file in files:
                    # Open all files
                    print('Testing'			,   lowercase_ )

                    if only_modules:
                           _lowerCamelCase       :		Optional[int]		=file.split('.' )[0]
                           try:
                                  _lowerCamelCase       :		Any		=getattr(lowercase_			,   lowercase_ )
                                  _lowerCamelCase       :		Optional[int]		=doctest.DocTestSuite(lowercase_ )
                                  _lowerCamelCase       :		List[Any]		=unittest.TextTestRunner().run(lowercase_ )
                                  self.assertIs(len(result.failures )			,   0 )
                           except AttributeError:
                                  logger.info(F'''{module_identifier} is not a module.''' )
                    else:
                           _lowerCamelCase       :		int		=doctest.testfile(str('..' / directory / file )			,   optionflags=doctest.ELLIPSIS )
                           self.assertIs(result.failed			,   0 )






      def        lowerCamelCase       (					self						:     Any )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		int		=Path('src/transformers' )
             _lowerCamelCase       :		Optional[Any]		='modeling'
             _lowerCamelCase       :		List[str]		=[
                 'modeling_ctrl.py',
                 'modeling_tf_ctrl.py',
             ]
             self.analyze_directory(lowercase_			,   identifier=lowercase_			,   ignore_files=lowercase_ )






      def        lowerCamelCase       (					self						:     List[str] )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=Path('src/transformers' )
             _lowerCamelCase       :		Union[str, Any]		='tokenization'
             self.analyze_directory(lowercase_			,   identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     Optional[int] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		str		=Path('src/transformers' )
             _lowerCamelCase       :		Any		='configuration'
             self.analyze_directory(lowercase_			,   identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     List[str] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=Path('src/transformers' )
             _lowerCamelCase       :		int		=['configuration', 'modeling', 'tokenization']
             self.analyze_directory(lowercase_			,   n_identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     Optional[Any] )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		str		=Path('docs/source' )
             _lowerCamelCase       :		Dict		=['favicon.ico']
             self.analyze_directory(lowercase_			,   ignore_files=lowercase_			,   only_modules=lowercase_ )


