'''simple docstring'''




import logging

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,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


__UpperCAmelCase					=logging.getLogger(__name__)




class        a__ (  a_					):






     def   SCREAMING_SNAKE_CASE__  (					self						:						str    ,							a						:						int    ,							a						:						List[Any]    ,							a						:						List[str]=None    ,							a						:						str=None       ):





         """simple docstring"""



         __lowerCamelCase            =    self.layer[current_layer](_a    ,							_a    ,							head_mask[current_layer]       )

         __lowerCamelCase            =    layer_outputs[0]

         return hidden_states




@add_start_docstrings(
    "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top."				,  a_				,  )
class        a__ (  a_					):






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





         """simple docstring"""



         super().__init__(_a       )

         __lowerCamelCase            =    BertEncoderWithPabee(_a       )

         self.init_weights()
         __lowerCamelCase            =    0
         __lowerCamelCase            =    0
         __lowerCamelCase            =    0

         __lowerCamelCase            =    0






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





         """simple docstring"""



         __lowerCamelCase            =    threshold






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





         """simple docstring"""



         __lowerCamelCase            =    patience






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    0
         __lowerCamelCase            =    0






     def   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.inference_layers_num / self.inference_instances_num
         __lowerCamelCase            =    (
             f"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="""
             f""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"""
         )
         print(_a       )






     @add_start_docstrings_to_model_forward(_a       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Union[str, Any]=None    ,							a						:						Any=None    ,							a						:						Optional[int]=None    ,							a						:						List[str]=None    ,							a						:						Dict=None    ,							a						:						Union[str, Any]=None    ,							a						:						Dict=None    ,							a						:						Union[str, Any]=None    ,							a						:						Optional[Any]=None    ,							a						:						Union[str, Any]=None    ,							a						:						Dict=False    ,							):





         """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 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 self.config.is_decoder and encoder_hidden_states is not None:
             __lowerCamelCase            =    encoder_hidden_states.size()
             __lowerCamelCase            =    (encoder_batch_size, encoder_sequence_length)
             if encoder_attention_mask is None:
                 __lowerCamelCase            =    torch.ones(_a    ,							device=_a       )
             __lowerCamelCase            =    self.invert_attention_mask(_a       )
         else:
             __lowerCamelCase            =    None

         # 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            =    embedding_output

         if self.training:
             __lowerCamelCase            =    []
             for i in range(self.config.num_hidden_layers       ):
                 __lowerCamelCase            =    self.encoder.adaptive_forward(
                     _a    ,							current_layer=_a    ,							attention_mask=_a    ,							head_mask=_a       )

                 __lowerCamelCase            =    self.pooler(_a       )
                 __lowerCamelCase            =    output_layers[i](output_dropout(_a       )       )
                 res.append(_a       )
         elif self.patience == 0:  # Use all layers for inference
             __lowerCamelCase            =    self.encoder(
                 _a    ,							attention_mask=_a    ,							head_mask=_a    ,							encoder_hidden_states=_a    ,							encoder_attention_mask=_a    ,							)
             __lowerCamelCase            =    self.pooler(encoder_outputs[0]       )
             __lowerCamelCase            =    [output_layers[self.config.num_hidden_layers - 1](_a       )]
         else:
             __lowerCamelCase            =    0
             __lowerCamelCase            =    None
             __lowerCamelCase            =    0
             for i in range(self.config.num_hidden_layers       ):
                 calculated_layer_num += 1
                 __lowerCamelCase            =    self.encoder.adaptive_forward(
                     _a    ,							current_layer=_a    ,							attention_mask=_a    ,							head_mask=_a       )

                 __lowerCamelCase            =    self.pooler(_a       )
                 __lowerCamelCase            =    output_layers[i](_a       )
                 if regression:
                     __lowerCamelCase            =    logits.detach()
                     if patient_result is not None:
                         __lowerCamelCase            =    patient_result.detach()
                     if (patient_result is not None) and torch.abs(patient_result - labels       ) < self.regression_threshold:
                         patient_counter += 1
                     else:
                         __lowerCamelCase            =    0
                 else:
                     __lowerCamelCase            =    logits.detach().argmax(dim=1       )
                     if patient_result is not None:
                         __lowerCamelCase            =    patient_result.detach().argmax(dim=1       )
                     if (patient_result is not None) and torch.all(labels.eq(_a       )       ):
                         patient_counter += 1
                     else:
                         __lowerCamelCase            =    0

                 __lowerCamelCase            =    logits
                 if patient_counter == self.patience:
                     break
             __lowerCamelCase            =    [patient_result]
             self.inference_layers_num += calculated_layer_num
             self.inference_instances_num += 1

         return res




@add_start_docstrings(
    "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. "				,  a_				,  )
class        a__ (  a_					):






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





         """simple docstring"""



         super().__init__(_a       )
         __lowerCamelCase            =    config.num_labels

         __lowerCamelCase            =    BertModelWithPabee(_a       )
         __lowerCamelCase            =    nn.Dropout(config.hidden_dropout_prob       )
         __lowerCamelCase            =    nn.ModuleList(
             [nn.Linear(config.hidden_size    ,							self.config.num_labels       ) for _ in range(config.num_hidden_layers       )]       )

         self.init_weights()






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





         """simple docstring"""



         __lowerCamelCase            =    self.bert(
             input_ids=_a    ,							attention_mask=_a    ,							token_type_ids=_a    ,							position_ids=_a    ,							head_mask=_a    ,							inputs_embeds=_a    ,							output_dropout=self.dropout    ,							output_layers=self.classifiers    ,							regression=self.num_labels == 1    ,							)

         __lowerCamelCase            =    (logits[-1],)

         if labels is not None:
             __lowerCamelCase            =    None
             __lowerCamelCase            =    0
             for ix, logits_item in enumerate(_a       ):
                 if self.num_labels == 1:
                     #  We are doing regression
                     __lowerCamelCase            =    MSELoss()
                     __lowerCamelCase            =    loss_fct(logits_item.view(-1       )    ,							labels.view(-1       )       )
                 else:
                     __lowerCamelCase            =    CrossEntropyLoss()
                     __lowerCamelCase            =    loss_fct(logits_item.view(-1    ,							self.num_labels       )    ,							labels.view(-1       )       )
                 if total_loss is None:
                     __lowerCamelCase            =    loss
                 else:
                     total_loss += loss * (ix + 1)
                 total_weights += ix + 1
             __lowerCamelCase            =    (total_loss / total_weights,) + outputs

         return outputs


"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_A     :			str  						=			logging.get_logger(__name__)

_A     :			Tuple  						=			{
    """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""",
    """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""",
    """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""",
    # See all BigBird models at https://huggingface.co/models?filter=big_bird
}

class 						a__		( a_		):
   __lowerCAmelCase				=							"""big_bird"""
   def __init__(     self      ,       _a=50_358      ,       _a=768      ,       _a=12      ,       _a=12      ,       _a=3_072      ,       _a="gelu_new"      ,       _a=0.1      ,       _a=0.1      ,       _a=4_096      ,       _a=2      ,       _a=0.0_2      ,       _a=1E-12      ,       _a=True      ,       _a=0      ,       _a=1      ,       _a=2      ,       _a=66      ,       _a="block_sparse"      ,       _a=True      ,       _a=False      ,       _a=64      ,       _a=3      ,       _a=None      ,       **_a      ,       ):
          super().__init__(
              pad_token_id=_a      ,       bos_token_id=_a      ,       eos_token_id=_a      ,       sep_token_id=_a      ,       **_a      ,       )

          lowercase       :							List[Any]									=				vocab_size
          lowercase       :							Optional[Any]									=				max_position_embeddings
          lowercase       :							str									=				hidden_size
          lowercase       :							int									=				num_hidden_layers
          lowercase       :							Optional[Any]									=				num_attention_heads
          lowercase       :							List[Any]									=				intermediate_size
          lowercase       :							int									=				hidden_act
          lowercase       :							str									=				hidden_dropout_prob
          lowercase       :							List[Any]									=				attention_probs_dropout_prob
          lowercase       :							Tuple									=				initializer_range
          lowercase       :							Optional[int]									=				type_vocab_size
          lowercase       :							str									=				layer_norm_eps
          lowercase       :							Tuple									=				use_cache

          lowercase       :							Any									=				rescale_embeddings
          lowercase       :							List[str]									=				attention_type
          lowercase       :							int									=				use_bias
          lowercase       :							Dict									=				block_size
          lowercase       :							List[str]									=				num_random_blocks
          lowercase       :							int									=				classifier_dropout


class 						a__		( a_		):
   @property
   def      __magic_name__     (     self							):
          if self.task == "multiple-choice":
                 lowercase       :							Union[str, Any]									=				{0: "batch", 1: "choice", 2: "sequence"}
          else:
                 lowercase       :							Dict									=				{0: "batch", 1: "sequence"}
          return OrderedDict(
              [
                  ("input_ids", dynamic_axis),
                  ("attention_mask", dynamic_axis),
              ]							)


