




"""simple docstring"""


import copy
import os
from typing import Union

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


A_      =    logging.get_logger(__name__)

A_      =    {
    '''BridgeTower/bridgetower-base''': '''https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json''',
    '''BridgeTower/bridgetower-base-itm-mlm''': (
        '''https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json'''
    ),
}






class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = "bridgetower_vision_model"


 def __init__(    self:		Optional[Any],				a_:		List[Any]=768,				a_:		Dict=12,				a_:		List[str]=3,				a_:		Union[str, Any]=16,				a_:		List[str]=288,				a_:		List[Any]=1,				a_:		List[Any]=1E-05,				a_:		int=False,				a_:		Optional[int]=True,				a_:		Optional[int]=False,				**a_:		Union[str, Any],				):




   '''simple docstring'''



   super().__init__(**a_		)
   _snake_case							:		Optional[int]								=  hidden_size
   _snake_case							:		str								=  num_hidden_layers
   _snake_case							:		Tuple								=  num_channels
   _snake_case							:		Tuple								=  patch_size
   _snake_case							:		Optional[int]								=  image_size
   _snake_case							:		str								=  initializer_factor
   _snake_case							:		List[str]								=  layer_norm_eps
   _snake_case							:		int								=  stop_gradient
   _snake_case							:		Optional[int]								=  share_layernorm
   _snake_case							:		List[Any]								=  remove_last_layer


 @classmethod
 def 			UpperCamelCase_       (    cls:		Tuple,				a_:		Union[str, os.PathLike],				**a_:		int		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		List[Any]								=  cls.get_config_dict(a_,				**a_		)

   if config_dict.get("""model_type"""		) == "bridgetower":
     _snake_case							:		int								=  config_dict["""text_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(a_,				**a_		)







class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = "bridgetower_text_model"


 def __init__(    self:		Optional[int],				a_:		Dict=50_265,				a_:		str=768,				a_:		int=12,				a_:		str=12,				a_:		Tuple=1,				a_:		Optional[int]=3_072,				a_:		Any="gelu",				a_:		Union[str, Any]=0.1,				a_:		List[Any]=0.1,				a_:		List[str]=514,				a_:		List[str]=1,				a_:		List[Any]=1E-05,				a_:		Optional[Any]=1,				a_:		List[Any]=0,				a_:		Any=2,				a_:		List[Any]="absolute",				a_:		Dict=True,				**a_:		str,				):




   '''simple docstring'''



   super().__init__(**a_		)

   _snake_case							:		str								=  vocab_size
   _snake_case							:		Optional[Any]								=  hidden_size
   _snake_case							:		Optional[Any]								=  num_hidden_layers
   _snake_case							:		Any								=  num_attention_heads
   _snake_case							:		int								=  hidden_act
   _snake_case							:		Optional[Any]								=  initializer_factor
   _snake_case							:		str								=  intermediate_size
   _snake_case							:		Union[str, Any]								=  hidden_dropout_prob
   _snake_case							:		int								=  attention_probs_dropout_prob
   _snake_case							:		int								=  max_position_embeddings
   _snake_case							:		List[Any]								=  type_vocab_size
   _snake_case							:		Union[str, Any]								=  layer_norm_eps
   _snake_case							:		Dict								=  position_embedding_type
   _snake_case							:		Any								=  use_cache
   _snake_case							:		str								=  pad_token_id
   _snake_case							:		Optional[Any]								=  bos_token_id
   _snake_case							:		Union[str, Any]								=  eos_token_id


 @classmethod
 def 			UpperCamelCase_       (    cls:		Optional[int],				a_:		Union[str, os.PathLike],				**a_:		int		):




   '''simple docstring'''



   _snake_case		, _snake_case							:		Any								=  cls.get_config_dict(a_,				**a_		)

   if config_dict.get("""model_type"""		) == "bridgetower":
     _snake_case							:		Optional[Any]								=  config_dict["""text_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(a_,				**a_		)







class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = "bridgetower"


 def __init__(    self:		Optional[int],				a_:		Optional[Any]=True,				a_:		Optional[int]="gelu",				a_:		Union[str, Any]=768,				a_:		Tuple=1,				a_:		Optional[int]=1E-05,				a_:		List[str]=False,				a_:		str="add",				a_:		str=12,				a_:		Dict=6,				a_:		Optional[Any]=False,				a_:		List[str]=False,				a_:		str=None,				a_:		int=None,				**a_:		Dict,				):




   '''simple docstring'''



   _snake_case							:		int								=  kwargs.pop("""text_config_dict""",				a_		)
   _snake_case							:		Any								=  kwargs.pop("""vision_config_dict""",				a_		)

   super().__init__(**a_		)
   _snake_case							:		int								=  share_cross_modal_transformer_layers
   _snake_case							:		int								=  hidden_act
   _snake_case							:		Tuple								=  hidden_size
   _snake_case							:		Tuple								=  initializer_factor
   _snake_case							:		str								=  layer_norm_eps
   _snake_case							:		Any								=  share_link_tower_layers
   _snake_case							:		Union[str, Any]								=  link_tower_type
   _snake_case							:		Dict								=  num_attention_heads
   _snake_case							:		Optional[Any]								=  num_hidden_layers
   _snake_case							:		Any								=  tie_word_embeddings
   _snake_case							:		Union[str, Any]								=  init_layernorm_from_vision_encoder

   if text_config is None:
     _snake_case							:		Dict								=  {}
     logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values."""		)

   if vision_config is None:
     _snake_case							:		Dict								=  {}
     logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values."""		)

   _snake_case							:		Union[str, Any]								=  BridgeTowerTextConfig(**a_		)
   _snake_case							:		str								=  BridgeTowerVisionConfig(**a_		)


 @classmethod
 def 			UpperCamelCase_       (    cls:		Optional[Any],				a_:		BridgeTowerTextConfig,				a_:		BridgeTowerVisionConfig,				**a_:		int		):




   '''simple docstring'''



   return cls(text_config=text_config.to_dict(),				vision_config=vision_config.to_dict(),				**a_		)


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Dict								=  copy.deepcopy(self.__dict__		)
   _snake_case							:		Any								=  self.text_config.to_dict()
   _snake_case							:		List[Any]								=  self.vision_config.to_dict()
   _snake_case							:		Tuple								=  self.__class__.model_type
   return output








"""simple docstring"""


import unicodedata
from dataclasses import dataclass
from typing import Optional, Union

import numpy as np

from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase


def  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Any		,       snake_case__							: List[str]		,       snake_case__							: int   ):
  """simple docstring"""

  if isinstance(snake_case__		,       snake_case__   ):
    _snake_case							:		List[Any]								=  np.full((len(snake_case__   ), sequence_length, 2)		,       snake_case__   )
  else:
    _snake_case							:		Any								=  np.full((len(snake_case__   ), sequence_length)		,       snake_case__   )

  for i, tensor in enumerate(snake_case__   ):
    if padding_side == "right":
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		Dict								=  tensor[:sequence_length]
      else:
        _snake_case							:		List[Any]								=  tensor[:sequence_length]
    else:
      if isinstance(snake_case__		,       snake_case__   ):
        _snake_case							:		str								=  tensor[:sequence_length]
      else:
        _snake_case							:		Tuple								=  tensor[:sequence_length]

  return out_tensor.tolist()


def  UpperCAmelCase__	(snake_case__							: Optional[int]   ):
  """simple docstring"""

  _snake_case							:		str								=  ord(snake_case__   )
  if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26):
    return True
  _snake_case							:		Union[str, Any]								=  unicodedata.category(snake_case__   )
  if cat.startswith("""P"""   ):
    return True
  return False






@dataclass
class  lowercase(					__a			):







 '''simple docstring'''





 lowercase__			 = 42
 lowercase__			 = True
 lowercase__			 = None
 lowercase__			 = None
 lowercase__			 = -1_00
 lowercase__			 = "pt"


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




   '''simple docstring'''



   import torch

   _snake_case							:		Optional[Any]								=  """label""" if """label""" in features[0].keys() else """labels"""
   _snake_case							:		str								=  [feature[label_name] for feature in features] if label_name in features[0].keys() else None
   _snake_case							:		Any								=  self.tokenizer.pad(
       a_,				padding=self.padding,				max_length=self.max_length,				pad_to_multiple_of=self.pad_to_multiple_of,				return_tensors="""pt""" if labels is None else None,				)

   if labels is None:
     return batch

   _snake_case							:		Optional[int]								=  torch.tensor(batch["""entity_ids"""]		).shape[1]
   _snake_case							:		Any								=  self.tokenizer.padding_side
   if padding_side == "right":
     _snake_case							:		Optional[int]								=  [
         list(a_		) + [self.label_pad_token_id] * (sequence_length - len(a_		)) for label in labels
     ]
   else:
     _snake_case							:		Union[str, Any]								=  [
         [self.label_pad_token_id] * (sequence_length - len(a_		)) + list(a_		) for label in labels
     ]

   _snake_case							:		List[Any]								=  [feature["""ner_tags"""] for feature in features]
   _snake_case							:		str								=  padding_tensor(a_,				-1,				a_,				a_		)
   _snake_case							:		Any								=  [feature["""original_entity_spans"""] for feature in features]
   _snake_case							:		int								=  padding_tensor(a_,				(-1, -1),				a_,				a_		)
   _snake_case							:		str								=  {k: torch.tensor(a_,				dtype=torch.intaa		) for k, v in batch.items()}

   return batch


