





"""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 SCREAMING_SNAKE_CASE_  (			snake_case  :   Optional[Any]						)->						Optional[Any]:
       _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   ,	a__  ):
            super().__init__()
            _lowerCamelCase             =   config.output_attentions
            _lowerCamelCase             =   config.output_hidden_states
            _lowerCamelCase             =   nn.ModuleList([BertLayer(_lowerCAmelCase  ) for _ in range(config.num_hidden_layers  )]  )
            _lowerCamelCase             =   nn.ModuleList([BertHighway(_lowerCAmelCase  ) for _ in range(config.num_hidden_layers  )]  )

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



     def 		snake_case_     (			self   ,	a__  ):
            if (type(_lowerCAmelCase  ) is float) or (type(_lowerCAmelCase  ) is int):
                   for i in range(len(self.early_exit_entropy  )  ):
                          _lowerCamelCase             =   x
            else:
                   _lowerCamelCase             =   x



     def 		snake_case_     (			self   ,	a__  ):
            _lowerCamelCase             =   pooler.state_dict()
            for highway in self.highway:
                   for name, param in highway.pooler.state_dict().items():
                          param.copy_(loaded_model[name]  )



     def 		snake_case_     (			self   ,	a__   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	):
            _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(
                       _lowerCAmelCase   ,	_lowerCAmelCase   ,	head_mask[i]   ,	_lowerCAmelCase   ,	_lowerCAmelCase  )
                   _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](_lowerCAmelCase  )
                   # logits, pooled_output

                   if not self.training:
                          _lowerCamelCase             =   highway_exit[0]
                          _lowerCamelCase             =   entropy(_lowerCAmelCase  )
                          _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(_lowerCAmelCase   ,	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). "      ,		_SCREAMING_SNAKE_CASE      ,		)
class       __a  (    _SCREAMING_SNAKE_CASE						):



     def __init__(			self   ,	a__  ):
            super().__init__(_lowerCAmelCase  )
            _lowerCamelCase             =   config

            _lowerCamelCase             =   BertEmbeddings(_lowerCAmelCase  )
            _lowerCamelCase             =   DeeBertEncoder(_lowerCAmelCase  )
            _lowerCamelCase             =   BertPooler(_lowerCAmelCase  )

            self.init_weights()



     def 		snake_case_     (			self  ):
            self.encoder.init_highway_pooler(self.pooler  )



     def 		snake_case_     (			self  ):
            return self.embeddings.word_embeddings



     def 		snake_case_     (			self   ,	a__  ):
            _lowerCamelCase             =   value



     def 		snake_case_     (			self   ,	a__  ):
            for layer, heads in heads_to_prune.items():
                   self.encoder.layer[layer].attention.prune_heads(_lowerCAmelCase  )



     @add_start_docstrings_to_model_forward(_lowerCAmelCase  )
     def 		snake_case_     (			self   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	):
            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(_lowerCAmelCase   ,	device=_lowerCAmelCase  )
            if encoder_attention_mask is None:
                   _lowerCamelCase             =   torch.ones(_lowerCAmelCase   ,	device=_lowerCAmelCase  )
            if token_type_ids is None:
                   _lowerCamelCase             =   torch.zeros(_lowerCAmelCase   ,	dtype=torch.long   ,	device=_lowerCAmelCase  )

            # 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(_lowerCAmelCase   ,	_lowerCAmelCase   ,	_lowerCAmelCase  )

            # 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(_lowerCAmelCase   ,	self.config.num_hidden_layers  )

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

            _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  (    _SCREAMING_SNAKE_CASE						):



     def __init__(			self   ,	a__   ,	a__  ):
            _lowerCamelCase             =   message
            _lowerCamelCase             =   exit_layer  # start from 1!







class       __a  (    nn.Module						):



     def __init__(			self   ,	a__  ):
            super().__init__()
            _lowerCamelCase             =   BertPooler(_lowerCAmelCase  )
            _lowerCamelCase             =   nn.Dropout(config.hidden_dropout_prob  )
            _lowerCamelCase             =   nn.Linear(config.hidden_size   ,	config.num_labels  )



     def 		snake_case_     (			self   ,	a__  ):
            # Pooler
            _lowerCamelCase             =   encoder_outputs[0]
            _lowerCamelCase             =   self.pooler(_lowerCAmelCase  )
            # "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(_lowerCAmelCase  )
            _lowerCamelCase             =   self.classifier(_lowerCAmelCase  )

            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. "      ,		_SCREAMING_SNAKE_CASE      ,		)
class       __a  (    _SCREAMING_SNAKE_CASE						):



     def __init__(			self   ,	a__  ):
            super().__init__(_lowerCAmelCase  )
            _lowerCamelCase             =   config.num_labels
            _lowerCamelCase             =   config.num_hidden_layers

            _lowerCamelCase             =   DeeBertModel(_lowerCAmelCase  )
            _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(_lowerCAmelCase  )
     def 		snake_case_     (			self   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=None   ,	a__=-1   ,	a__=False   ,	):
            _lowerCamelCase             =   self.num_layers
            try:
                   _lowerCamelCase             =   self.bert(
                       _lowerCAmelCase   ,	attention_mask=_lowerCAmelCase   ,	token_type_ids=_lowerCAmelCase   ,	position_ids=_lowerCAmelCase   ,	head_mask=_lowerCAmelCase   ,	inputs_embeds=_lowerCAmelCase   ,	)
                   # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

                   _lowerCamelCase             =   outputs[1]

                   _lowerCamelCase             =   self.dropout(_lowerCAmelCase  )
                   _lowerCamelCase             =   self.classifier(_lowerCAmelCase  )
                   _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(_lowerCAmelCase  )
                   _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(_lowerCAmelCase  )
                                 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(_lowerCAmelCase  )

                   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)












from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__					:  str      							=				logging.get_logger(__name__)

lowerCamelCase__					:  Tuple      							=				{
    'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/config.json',
    'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json',
    'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/config.json',
    'funnel-transformer/medium-base': 'https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json',
    'funnel-transformer/intermediate': (
        'https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json'
    ),
    'funnel-transformer/intermediate-base': (
        'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json'
    ),
    'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/config.json',
    'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json',
    'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json',
    'funnel-transformer/xlarge-base': 'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json',
}





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       "funnel"
 lowercase_							       =       {
     "hidden_size": "d_model",
     "num_attention_heads": "n_head",
 }



 def __init__(				self    :						int							,							_lowerCAmelCase    :						Optional[int]=30_522							,							_lowerCAmelCase    :						List[str]=[4, 4, 4]							,							_lowerCAmelCase    :						Tuple=None							,							_lowerCAmelCase    :						Optional[int]=2							,							_lowerCAmelCase    :						int=768							,							_lowerCAmelCase    :						Optional[Any]=12							,							_lowerCAmelCase    :						Optional[Any]=64							,							_lowerCAmelCase    :						Optional[Any]=3_072							,							_lowerCAmelCase    :						List[str]="gelu_new"							,							_lowerCAmelCase    :						Any=0.1							,							_lowerCAmelCase    :						int=0.1							,							_lowerCAmelCase    :						Tuple=0.0							,							_lowerCAmelCase    :						List[Any]=0.1							,							_lowerCAmelCase    :						Dict=None							,							_lowerCAmelCase    :						str=1E-9							,							_lowerCAmelCase    :						Any="mean"							,							_lowerCAmelCase    :						Union[str, Any]="relative_shift"							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Dict=True							,							_lowerCAmelCase    :						Tuple=True							,							**_lowerCAmelCase    :						Optional[Any]							,							):
       SCREAMING_SNAKE_CASE_      		=     vocab_size
       SCREAMING_SNAKE_CASE_      		=     block_sizes
       SCREAMING_SNAKE_CASE_      		=     [1] * len(_lowerCAmelCase		) if block_repeats is None else block_repeats
       assert len(_lowerCAmelCase		) == len(
           self.block_repeats		), "`block_sizes` and `block_repeats` should have the same length."
       SCREAMING_SNAKE_CASE_      		=     num_decoder_layers
       SCREAMING_SNAKE_CASE_      		=     d_model
       SCREAMING_SNAKE_CASE_      		=     n_head
       SCREAMING_SNAKE_CASE_      		=     d_head
       SCREAMING_SNAKE_CASE_      		=     d_inner
       SCREAMING_SNAKE_CASE_      		=     hidden_act
       SCREAMING_SNAKE_CASE_      		=     hidden_dropout
       SCREAMING_SNAKE_CASE_      		=     attention_dropout
       SCREAMING_SNAKE_CASE_      		=     activation_dropout
       SCREAMING_SNAKE_CASE_      		=     initializer_range
       SCREAMING_SNAKE_CASE_      		=     initializer_std
       SCREAMING_SNAKE_CASE_      		=     layer_norm_eps
       assert pooling_type in [
           "mean",
           "max",
       ], F"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
       SCREAMING_SNAKE_CASE_      		=     pooling_type
       assert attention_type in [
           "relative_shift",
           "factorized",
       ], F"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
       SCREAMING_SNAKE_CASE_      		=     attention_type
       SCREAMING_SNAKE_CASE_      		=     separate_cls
       SCREAMING_SNAKE_CASE_      		=     truncate_seq
       SCREAMING_SNAKE_CASE_      		=     pool_q_only

       super().__init__(**_lowerCAmelCase		)



 @property
 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       return sum(self.block_sizes		)



 @num_hidden_layers.setter
 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						List[Any]		):
       raise NotImplementedError(
           'This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.'		)



 @property
 def  lowerCAmelCase_    (				self    :						List[Any]		):
       return len(self.block_sizes		)




 @num_blocks.setter
 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Union[str, Any]		):
       raise NotImplementedError('This model does not support the setting of `num_blocks`. Please set `block_sizes`.'		)