


"""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       A_   (   _lowerCAmelCase     :					Union[str, Any]       ):






     """simple docstring"""

     _a    	=				torch.exp(a__       )
     _a    	=				torch.sum(a__,     dim=1       )  # sum of exp(x_i)
     _a    	=				torch.sum(x * exp_x,     dim=1       )  # sum of x_i * exp(x_i)
     return torch.log(a__       ) - B / A


class     __lowerCamelCase  (					nn.Module				):

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase							)       ->							Optional[int]:
          super().__init__()
          _a    	=				config.output_attentions
          _a    	=				config.output_hidden_states
          _a    	=				nn.ModuleList([BertLayer(__A							) for _ in range(config.num_hidden_layers							)]							)
          _a    	=				nn.ModuleList([BertHighway(__A							) for _ in range(config.num_hidden_layers							)]							)

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


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							Union[str, Any]:
          if (type(__A							) is float) or (type(__A							) is int):
               for i in range(len(self.early_exit_entropy							)							):
                    _a    	=				x
          else:
               _a    	=				x


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							Union[str, Any]:
          _a    	=				pooler.state_dict()
          for highway in self.highway:
               for name, param in highway.pooler.state_dict().items():
                    param.copy_(loaded_model[name]							)





     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				)       ->							Union[str, Any]:
          _a    	=				()
          _a    	=				()
          _a    	=				()
          for i, layer_module in enumerate(self.layer							):
               if self.output_hidden_states:
                    _a    	=				all_hidden_states + (hidden_states,)

               _a    	=				layer_module(
                   __A    ,				__A    ,				head_mask[i]    ,				__A    ,				__A							)
               _a    	=				layer_outputs[0]

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

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

               _a    	=				self.highway[i](__A							)
               # logits, pooled_output

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

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

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

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

          _a    	=				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). '  ,					__lowercase  ,					)
class     __lowerCamelCase  (					__lowercase				):

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase							)       ->							Dict:
          super().__init__(__A							)
          _a    	=				config

          _a    	=				BertEmbeddings(__A							)
          _a    	=				DeeBertEncoder(__A							)
          _a    	=				BertPooler(__A							)

          self.init_weights()


     def 							_UpperCAmelCase      (      self							)       ->							Dict:
          self.encoder.init_highway_pooler(self.pooler							)


     def 							_UpperCAmelCase      (      self							)       ->							Any:
          return self.embeddings.word_embeddings


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							Tuple:
          _a    	=				value


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							List[str]:
          for layer, heads in heads_to_prune.items():
               self.encoder.layer[layer].attention.prune_heads(__A							)





     @add_start_docstrings_to_model_forward(__A							)
     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				)       ->							int:
          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:
               _a    	=				input_ids.size()
          elif inputs_embeds is not None:
               _a    	=				inputs_embeds.size()[:-1]
          else:
               raise ValueError('''You have to specify either input_ids or inputs_embeds'''							)

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

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

          _a    	=				encoder_extended_attention_mask.to(
              dtype=next(self.parameters()							).dtype							)  # fp16 compatibility
          _a    	=				(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]
          _a    	=				self.get_head_mask(__A    ,				self.config.num_hidden_layers							)

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

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

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase							)       ->							Dict:
          _a    	=				message
          _a    	=				exit_layer  # start from 1!







class     __lowerCamelCase  (					nn.Module				):

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase							)       ->							int:
          super().__init__()
          _a    	=				BertPooler(__A							)
          _a    	=				nn.Dropout(config.hidden_dropout_prob							)
          _a    	=				nn.Linear(config.hidden_size    ,				config.num_labels							)





     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							int:
          # Pooler
          _a    	=				encoder_outputs[0]
          _a    	=				self.pooler(__A							)
          # "return" pooler_output

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

          # Dropout and classification
          _a    	=				bmodel_output[1]

          _a    	=				self.dropout(__A							)
          _a    	=				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. '  ,					__lowercase  ,					)
class     __lowerCamelCase  (					__lowercase				):

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase							)       ->							Union[str, Any]:
          super().__init__(__A							)
          _a    	=				config.num_labels
          _a    	=				config.num_hidden_layers

          _a    	=				DeeBertModel(__A							)
          _a    	=				nn.Dropout(config.hidden_dropout_prob							)
          _a    	=				nn.Linear(config.hidden_size    ,				self.config.num_labels							)

          self.init_weights()





     @add_start_docstrings_to_model_forward(__A							)
     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=None    ,				__UpperCAmelCase=-1    ,				__UpperCAmelCase=False    ,				)       ->							Tuple:
          _a    	=				self.num_layers
          try:
               _a    	=				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

               _a    	=				outputs[1]

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

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

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

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



"""simple docstring"""






from typing import Any
def       A_   (   _lowerCAmelCase     :					list       ):






     """simple docstring"""

     if not input_list:
          return []
     _a    	=				[input_list.count(_lowerCAmelCase       ) for value in input_list]
     _a    	=				max(_lowerCAmelCase       )  # Gets the maximum count in the input list.
     # Gets values of modes
     return sorted({input_list[i] for i, value in enumerate(_lowerCAmelCase       ) if value == y}       )


if __name__ == "__main__":
   import doctest

   doctest.testmod()