




"""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 copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


__magic_name__       =			logging.get_logger(__name__)

__magic_name__       =			{
    "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		'''blip_2_vision_model'''




		def __init__(     self							,  lowerCAmelCase__=1_4_0_8							,  lowerCAmelCase__=6_1_4_4							,  lowerCAmelCase__=3_9							,  lowerCAmelCase__=1_6							,  lowerCAmelCase__=2_2_4							,  lowerCAmelCase__=1_4							,  lowerCAmelCase__="gelu"							,  lowerCAmelCase__=0.0_00_01							,  lowerCAmelCase__=0.0							,  lowerCAmelCase__=1E-10							,  lowerCAmelCase__=True							,  **lowerCAmelCase__							,  ):
				super().__init__(**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = hidden_size
				__SCREAMING_SNAKE_CASE            = intermediate_size
				__SCREAMING_SNAKE_CASE            = num_hidden_layers
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = patch_size
				__SCREAMING_SNAKE_CASE            = image_size
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = attention_dropout
				__SCREAMING_SNAKE_CASE            = layer_norm_eps
				__SCREAMING_SNAKE_CASE            = hidden_act
				__SCREAMING_SNAKE_CASE            = qkv_bias




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				cls._set_token_in_kwargs(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = cls.get_config_dict(lowerCAmelCase__							,  **lowerCAmelCase__)

				# get the vision config dict if we are loading from Blip2Config
				if config_dict.get("""model_type""") == "blip-2":
						__SCREAMING_SNAKE_CASE            = config_dict["""vision_config"""]

				if "model_type" in config_dict and hasattr(cls							,  """model_type""") and config_dict["model_type"] != cls.model_type:
						logger.warning(
						    f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
						    f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")

				return cls.from_dict(lowerCAmelCase__							,  **lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Tuple						   =		'''blip_2_qformer'''




		def __init__(     self							,  lowerCAmelCase__=3_0_5_2_2							,  lowerCAmelCase__=7_6_8							,  lowerCAmelCase__=1_2							,  lowerCAmelCase__=1_2							,  lowerCAmelCase__=3_0_7_2							,  lowerCAmelCase__="gelu"							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=5_1_2							,  lowerCAmelCase__=0.02							,  lowerCAmelCase__=1E-12							,  lowerCAmelCase__=0							,  lowerCAmelCase__="absolute"							,  lowerCAmelCase__=2							,  lowerCAmelCase__=1_4_0_8							,  **lowerCAmelCase__							,  ):
				super().__init__(pad_token_id=lowerCAmelCase__							,  **lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = vocab_size
				__SCREAMING_SNAKE_CASE            = hidden_size
				__SCREAMING_SNAKE_CASE            = num_hidden_layers
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = hidden_act
				__SCREAMING_SNAKE_CASE            = intermediate_size
				__SCREAMING_SNAKE_CASE            = hidden_dropout_prob
				__SCREAMING_SNAKE_CASE            = attention_probs_dropout_prob
				__SCREAMING_SNAKE_CASE            = max_position_embeddings
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = layer_norm_eps
				__SCREAMING_SNAKE_CASE            = position_embedding_type
				__SCREAMING_SNAKE_CASE            = cross_attention_frequency
				__SCREAMING_SNAKE_CASE            = encoder_hidden_size




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				cls._set_token_in_kwargs(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = cls.get_config_dict(lowerCAmelCase__							,  **lowerCAmelCase__)

				# get the qformer config dict if we are loading from Blip2Config
				if config_dict.get("""model_type""") == "blip-2":
						__SCREAMING_SNAKE_CASE            = config_dict["""qformer_config"""]

				if "model_type" in config_dict and hasattr(cls							,  """model_type""") and config_dict["model_type"] != cls.model_type:
						logger.warning(
						    f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
						    f"{cls.model_type}. This is not supported for all configurations of models and can yield errors.")

				return cls.from_dict(lowerCAmelCase__							,  **lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		'''blip-2'''
		__lowercase							:  Any						   =		True




		def __init__(     self							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None							,  lowerCAmelCase__=3_2							,  **lowerCAmelCase__):
				super().__init__(**lowerCAmelCase__)

				if vision_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""")

				if qformer_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""")

				if text_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""")

				__SCREAMING_SNAKE_CASE            = BlipaVisionConfig(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = BlipaQFormerConfig(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = text_config["""model_type"""] if """model_type""" in text_config else """opt"""
				__SCREAMING_SNAKE_CASE            = CONFIG_MAPPING[text_model_type](**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.text_config.tie_word_embeddings
				__SCREAMING_SNAKE_CASE            = self.text_config.is_encoder_decoder

				__SCREAMING_SNAKE_CASE            = num_query_tokens
				__SCREAMING_SNAKE_CASE            = self.vision_config.hidden_size
				__SCREAMING_SNAKE_CASE            = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
				__SCREAMING_SNAKE_CASE            = 1.0
				__SCREAMING_SNAKE_CASE            = 0.02




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  **lowerCAmelCase__							,  ):
				return cls(
				    vision_config=vision_config.to_dict()							,  qformer_config=qformer_config.to_dict()							,  text_config=text_config.to_dict()							,  **lowerCAmelCase__							,  )




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = copy.deepcopy(self.__dict__)
				__SCREAMING_SNAKE_CASE            = self.vision_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.qformer_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.text_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.__class__.model_type
				return output




