




"""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 					UpperCAmelCase__       (snake_case__							:					Optional[Any]    ):
  """simple docstring"""

  _snake_case							:		Optional[int]								=  torch.exp(snake_case__    )
  _snake_case							:		List[str]								=  torch.sum(snake_case__		,   dim=1    )  # sum of exp(x_i)
  _snake_case							:		List[str]								=  torch.sum(x * exp_x		,   dim=1    )  # sum of x_i * exp(x_i)
  return torch.log(snake_case__    ) - B / A






class 					lowercase(     nn.Module ):







 '''simple docstring'''





 def __init__(				self:		str,      a_:		Dict		):




   '''simple docstring'''



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

   _snake_case							:		Dict								=  [-1 for _ in range(config.num_hidden_layers		)]


 def  UpperCamelCase_   (				self:		str,      a_:		List[Any]		):




   '''simple docstring'''



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


 def  UpperCamelCase_   (				self:		List[str],      a_:		Optional[Any]		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  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:		Union[str, Any],      a_:		List[Any],      a_:		Union[str, Any]=None,      a_:		Any=None,      a_:		Union[str, Any]=None,      a_:		Optional[Any]=None,      ):




   '''simple docstring'''



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

     _snake_case							:		Any								=  layer_module(
         a_,      a_,      head_mask[i],      a_,      a_		)
     _snake_case							:		Optional[int]								=  layer_outputs[0]

     if self.output_attentions:
       _snake_case							:		List[Any]								=  all_attentions + (layer_outputs[1],)

     _snake_case							:		Optional[int]								=  (hidden_states,)
     if self.output_hidden_states:
       _snake_case							:		Any								=  current_outputs + (all_hidden_states,)
     if self.output_attentions:
       _snake_case							:		int								=  current_outputs + (all_attentions,)

     _snake_case							:		Union[str, Any]								=  self.highway[i](a_		)
     # logits, pooled_output

     if not self.training:
       _snake_case							:		Optional[int]								=  highway_exit[0]
       _snake_case							:		Tuple								=  entropy(a_		)
       _snake_case							:		Union[str, Any]								=  highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
       _snake_case							:		Any								=  all_highway_exits + (highway_exit,)

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

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

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

   _snake_case							:		int								=  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). "       ,			__a       ,			)
class 					lowercase(     __a ):







 '''simple docstring'''





 def __init__(				self:		Dict,      a_:		int		):




   '''simple docstring'''



   super().__init__(a_		)
   _snake_case							:		Dict								=  config

   _snake_case							:		List[str]								=  BertEmbeddings(a_		)
   _snake_case							:		Dict								=  DeeBertEncoder(a_		)
   _snake_case							:		int								=  BertPooler(a_		)

   self.init_weights()


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   self.encoder.init_highway_pooler(self.pooler		)


 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   return self.embeddings.word_embeddings


 def  UpperCamelCase_   (				self:		Optional[Any],      a_:		int		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  value


 def  UpperCamelCase_   (				self:		Any,      a_:		int		):




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

   _snake_case							:		str								=  input_ids.device if input_ids is not None else inputs_embeds.device

   if attention_mask is None:
     _snake_case							:		List[Any]								=  torch.ones(a_,      device=a_		)
   if encoder_attention_mask is None:
     _snake_case							:		Optional[int]								=  torch.ones(a_,      device=a_		)
   if token_type_ids is None:
     _snake_case							:		Optional[int]								=  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.
   _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:
     _snake_case							:		Dict								=  encoder_attention_mask[:, None, :, :]
   if encoder_attention_mask.dim() == 2:
     _snake_case							:		Optional[int]								=  encoder_attention_mask[:, None, None, :]

   _snake_case							:		List[str]								=  encoder_extended_attention_mask.to(
       dtype=next(self.parameters()		).dtype		)  # fp16 compatibility
   _snake_case							:		Union[str, Any]								=  (1.0 - encoder_extended_attention_mask) * -10_000.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]
   _snake_case							:		Optional[Any]								=  self.get_head_mask(a_,      self.config.num_hidden_layers		)

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

   _snake_case							:		Optional[Any]								=  (
       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 					lowercase(     __a ):







 '''simple docstring'''





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




   '''simple docstring'''



   _snake_case							:		Tuple								=  message
   _snake_case							:		Tuple								=  exit_layer  # start from 1!







class 					lowercase(     nn.Module ):







 '''simple docstring'''





 def __init__(				self:		List[str],      a_:		Tuple		):




   '''simple docstring'''



   super().__init__()
   _snake_case							:		List[str]								=  BertPooler(a_		)
   _snake_case							:		Optional[int]								=  nn.Dropout(config.hidden_dropout_prob		)
   _snake_case							:		str								=  nn.Linear(config.hidden_size,      config.num_labels		)


 def  UpperCamelCase_   (				self:		Optional[int],      a_:		List[str]		):




   '''simple docstring'''



   _snake_case							:		Dict								=  encoder_outputs[0]
   _snake_case							:		List[Any]								=  self.pooler(a_		)
   # "return" pooler_output

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

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

   _snake_case							:		int								=  self.dropout(a_		)
   _snake_case							:		List[Any]								=  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. "       ,			__a       ,			)
class 					lowercase(     __a ):







 '''simple docstring'''





 def __init__(				self:		str,      a_:		Dict		):




   '''simple docstring'''



   super().__init__(a_		)
   _snake_case							:		Optional[Any]								=  config.num_labels
   _snake_case							:		List[str]								=  config.num_hidden_layers

   _snake_case							:		Union[str, Any]								=  DeeBertModel(a_		)
   _snake_case							:		List[str]								=  nn.Dropout(config.hidden_dropout_prob		)
   _snake_case							:		Tuple								=  nn.Linear(config.hidden_size,      self.config.num_labels		)

   self.init_weights()


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




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  self.num_layers
   try:
     _snake_case							:		Dict								=  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

     _snake_case							:		Dict								=  outputs[1]

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

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

     # work with highway exits
     _snake_case							:		Optional[Any]								=  []
     for highway_exit in outputs[-1]:
       _snake_case							:		List[Any]								=  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
         _snake_case							:		Dict								=  MSELoss()
         _snake_case							:		Optional[Any]								=  loss_fct(highway_logits.view(-1		),      labels.view(-1		)		)
       else:
         _snake_case							:		Optional[int]								=  CrossEntropyLoss()
         _snake_case							:		str								=  loss_fct(highway_logits.view(-1,      self.num_labels		),      labels.view(-1		)		)
       highway_losses.append(a_		)

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


import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin






class 					lowercase(     __a ):







 '''simple docstring'''





 lowercase__ 					=					["image_processor", "tokenizer"]
 lowercase__ 					=					"AutoImageProcessor"
 lowercase__ 					=					"AutoTokenizer"


 def __init__(				self:		List[str],      a_:		List[str]=None,      a_:		Tuple=None,      **a_:		Tuple		):




   '''simple docstring'''



   _snake_case							:		str								=  None
   if "feature_extractor" in kwargs:
     warnings.warn(
         """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
         """ instead.""",      a_,      )
     _snake_case							:		str								=  kwargs.pop("""feature_extractor"""		)

   _snake_case							:		Union[str, Any]								=  image_processor if image_processor is not None else feature_extractor
   if image_processor is None:
     raise ValueError("""You need to specify an `image_processor`."""		)
   if tokenizer is None:
     raise ValueError("""You need to specify a `tokenizer`."""		)

   super().__init__(a_,      a_		)
   _snake_case							:		Dict								=  self.image_processor
   _snake_case							:		Any								=  False


 def __call__(				self:		Any,      *a_:		Any,      **a_:		Tuple		):




   '''simple docstring'''



   if self._in_target_context_manager:
     return self.current_processor(*a_,      **a_		)

   _snake_case							:		Dict								=  kwargs.pop("""images""",      a_		)
   _snake_case							:		Optional[Any]								=  kwargs.pop("""text""",      a_		)
   if len(a_		) > 0:
     _snake_case							:		Optional[int]								=  args[0]
     _snake_case							:		Tuple								=  args[1:]

   if images is None and text is None:
     raise ValueError("""You need to specify either an `images` or `text` input to process."""		)

   if images is not None:
     _snake_case							:		Tuple								=  self.image_processor(a_,      *a_,      **a_		)
   if text is not None:
     _snake_case							:		Tuple								=  self.tokenizer(a_,      **a_		)

   if text is None:
     return inputs
   elif images is None:
     return encodings
   else:
     _snake_case							:		List[str]								=  encodings["""input_ids"""]
     return inputs


 def  UpperCamelCase_   (				self:		Optional[int],      *a_:		Tuple,      **a_:		List[str]		):




   '''simple docstring'''



   return self.tokenizer.batch_decode(*a_,      **a_		)


 def  UpperCamelCase_   (				self:		int,      *a_:		List[str],      **a_:		int		):




   '''simple docstring'''



   return self.tokenizer.decode(*a_,      **a_		)


 @contextmanager
 def  UpperCamelCase_   (				self:		Dict		):




   '''simple docstring'''



   warnings.warn(
       """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
       """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
       """your images inputs, or in a separate call."""		)
   _snake_case							:		Any								=  True
   _snake_case							:		Optional[int]								=  self.tokenizer
   yield
   _snake_case							:		int								=  self.image_processor
   _snake_case							:		Optional[int]								=  False


 def  UpperCamelCase_   (				self:		Dict,      a_:		Optional[Any],      a_:		str=False,      a_:		Optional[Any]=None		):




   '''simple docstring'''



   if added_vocab is None:
     _snake_case							:		Dict								=  self.tokenizer.get_added_vocab()

   _snake_case							:		str								=  {}

   while tokens:
     _snake_case							:		Union[str, Any]								=  re.search(r"""<s_(.*?)>""",      a_,      re.IGNORECASE		)
     if start_token is None:
       break
     _snake_case							:		List[Any]								=  start_token.group(1		)
     _snake_case							:		str								=  re.search(rf"</s_{key}>",      a_,      re.IGNORECASE		)
     _snake_case							:		Dict								=  start_token.group()
     if end_token is None:
       _snake_case							:		List[Any]								=  tokens.replace(a_,      """"""		)
     else:
       _snake_case							:		List[str]								=  end_token.group()
       _snake_case							:		str								=  re.escape(a_		)
       _snake_case							:		str								=  re.escape(a_		)
       _snake_case							:		Union[str, Any]								=  re.search(f"{start_token_escaped}(.*?){end_token_escaped}",      a_,      re.IGNORECASE		)
       if content is not None:
         _snake_case							:		int								=  content.group(1		).strip()
         if r"<s_" in content and r"</s_" in content:  # non-leaf node
           _snake_case							:		List[Any]								=  self.tokenajson(a_,      is_inner_value=a_,      added_vocab=a_		)
           if value:
             if len(a_		) == 1:
               _snake_case							:		List[str]								=  value[0]
             _snake_case							:		List[str]								=  value
         else:  # leaf nodes
           _snake_case							:		Tuple								=  []
           for leaf in content.split(r"""<sep/>"""		):
             _snake_case							:		Tuple								=  leaf.strip()
             if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
               _snake_case							:		int								=  leaf[1:-2]  # for categorical special tokens
             output[key].append(a_		)
           if len(output[key]		) == 1:
             _snake_case							:		int								=  output[key][0]

       _snake_case							:		Any								=  tokens[tokens.find(a_		) + len(a_		) :].strip()
       if tokens[:6] == r"<sep/>":  # non-leaf nodes
         return [output] + self.tokenajson(tokens[6:],      is_inner_value=a_,      added_vocab=a_		)

   if len(a_		):
     return [output] if is_inner_value else output
   else:
     return [] if is_inner_value else {"text_sequence": tokens}


 @property
 def  UpperCamelCase_   (				self:		Optional[int]		):




   '''simple docstring'''



   warnings.warn(
       """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""",      a_,      )
   return self.image_processor_class


 @property
 def  UpperCamelCase_   (				self:		Tuple		):




   '''simple docstring'''



   warnings.warn(
       """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""",      a_,      )
   return self.image_processor


