


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,
)


SCREAMING_SNAKE_CASE							    =							logging.getLogger(__name__)


class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A=None  ,       __A=None    ):
        __a					=  self.layer[current_layer](__A  ,       __A  ,       head_mask[current_layer]    )

        __a					=  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     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def __init__(	self  ,       __A    ):
        super().__init__(__A    )

        __a					=  BertEncoderWithPabee(__A    )

        self.init_weights()
        __a					=  0
        __a					=  0
        __a					=  0

        __a					=  0


     def 	snake_case_  (	self  ,       __A    ):
        __a					=  threshold


     def 	snake_case_  (	self  ,       __A    ):
        __a					=  patience


     def 	snake_case_  (	self    ):
        __a					=  0
        __a					=  0


     def 	snake_case_  (	self    ):
        __a					=  self.inference_layers_num / self.inference_instances_num
        __a					=  (
            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 	snake_case_  (	self  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=False  ,       ):

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

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

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

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

              __a					=  logits
              if patient_counter == self.patience:
                 break
           __a					=  [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
    the pooled output) e.g. for GLUE tasks. """ ,					__A ,					)
class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def __init__(	self  ,       __A    ):
        super().__init__(__A    )
        __a					=  config.num_labels

        __a					=  BertModelWithPabee(__A    )
        __a					=  nn.Dropout(config.hidden_dropout_prob    )
        __a					=  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 	snake_case_  (	self  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       ):
        __a					=  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  ,       )

        __a					=  (logits[-1],)

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

        return outputs






import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):
    __UpperCamelCase    =["image_processor", "tokenizer"]
    __UpperCamelCase    ="CLIPImageProcessor"
    __UpperCamelCase    =("CLIPTokenizer", "CLIPTokenizerFast")

    def __init__(      self			:   int				,     snake_case__			:   List[Any]=None				,     snake_case__			:   Any=None				,     **snake_case__			:   Any     ):

     """simple docstring"""






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

     SCREAMING_SNAKE_CASE		    =      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__(snake_case__				,     snake_case__     )

    def __call__(      self			:   List[Any]				,     snake_case__			:   Tuple=None				,     snake_case__			:   Optional[int]=None				,     snake_case__			:   List[str]=None				,     **snake_case__			:   Dict     ):

     """simple docstring"""






     if text is None and images is None:
      raise ValueError('You have to specify either text or images. Both cannot be none.'     )

     if text is not None:
      SCREAMING_SNAKE_CASE		    =      self.tokenizer(snake_case__				,     return_tensors=snake_case__				,     **snake_case__     )

     if images is not None:
      SCREAMING_SNAKE_CASE		    =      self.image_processor(snake_case__				,     return_tensors=snake_case__				,     **snake_case__     )

     if text is not None and images is not None:
      SCREAMING_SNAKE_CASE		    =      image_features.pixel_values
      return encoding
     elif text is not None:
      return encoding
     else:
      return BatchEncoding(data=dict(**snake_case__     )				,     tensor_type=snake_case__     )

    def UpperCamelCase      (      self			:   Union[str, Any]				,     *snake_case__			:   Optional[Any]				,     **snake_case__			:   Optional[int]     ):

     """simple docstring"""






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

    def UpperCamelCase      (      self			:   Dict				,     *snake_case__			:   Optional[Any]				,     **snake_case__			:   Dict     ):

     """simple docstring"""






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

    @property
    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.tokenizer.model_input_names
     SCREAMING_SNAKE_CASE		    =      self.image_processor.model_input_names
     return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names     )     )

    @property
    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     warnings.warn(
         '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'				,     snake_case__				,     )
     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.'				,     snake_case__				,     )
     return self.image_processor

