





import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_snake_case    :       str		       =    logging.get_logger(__name__)

_snake_case    :       Tuple		       =    list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_snake_case    :       Union[str, Any]		       =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Model type selected in the list: """ + """, """.join(_UpperCamelCase       )}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}       )
  a_              =					field(
      default=1_28						,       metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }						,       )
  a_              =					field(
      default=1_28						,       metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,       )
  a_              =					field(
      default=64						,       metadata={
          """help""": (
              """The maximum number of tokens for the question. Questions longer than this will """
              """be truncated to this length."""
          )
      }						,       )
  a_              =					field(
      default=30						,       metadata={
          """help""": (
              """The maximum length of an answer that can be generated. This is needed because the start """
              """and end predictions are not conditioned on one another."""
          )
      }						,       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}       )
  a_              =					field(
      default=0.0						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=20						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=0						,       metadata={
          """help""": (
              """language id of input for language-specific xlm models (see"""
              """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
          )
      }						,       )
  a_              =					field(default=1						,       metadata={"""help""": """multiple threads for converting example to features"""}       )





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					"""train"""
  a_              =					"""dev"""





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42






  def __init__(							self					:						int   ,    lowerCAmelCase_					:						SquadDataTrainingArguments   ,    lowerCAmelCase_					:						PreTrainedTokenizer   ,    lowerCAmelCase_					:						Optional[int] = None   ,    lowerCAmelCase_					:						Union[str, Split] = Split.train   ,    lowerCAmelCase_					:						Optional[bool] = False   ,    lowerCAmelCase_					:						Optional[str] = None   ,    lowerCAmelCase_					:						Optional[str] = "pt"   ,    )				->		Tuple:
     __lowerCAmelCase				      =      args
     __lowerCAmelCase				      =      is_language_sensitive
     __lowerCAmelCase				      =      SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
     if isinstance(lowerCAmelCase_   ,    lowerCAmelCase_	):
        try:
           __lowerCAmelCase				      =      Split[mode]
        except KeyError:
           raise KeyError('mode is not a valid split name'	)
     __lowerCAmelCase				      =      mode
     # Load data features from cache or dataset file
     __lowerCAmelCase				      =      'v2' if args.version_2_with_negative else 'v1'
     __lowerCAmelCase				      =      os.path.join(
         cache_dir if cache_dir is not None else args.data_dir   ,    f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"""   ,    )

     # Make sure only the first process in distributed training processes the dataset,
     # and the others will use the cache.
     __lowerCAmelCase				      =      cached_features_file + '.lock'
     with FileLock(lowerCAmelCase_	):
        if os.path.exists(lowerCAmelCase_	) and not args.overwrite_cache:
           __lowerCAmelCase				      =      time.time()
           __lowerCAmelCase				      =      torch.load(lowerCAmelCase_	)

           # Legacy cache files have only features, while new cache files
           # will have dataset and examples also.
           __lowerCAmelCase				      =      self.old_features['features']
           __lowerCAmelCase				      =      self.old_features.get('dataset'   ,    lowerCAmelCase_	)
           __lowerCAmelCase				      =      self.old_features.get('examples'   ,    lowerCAmelCase_	)
           logger.info(
               f"""Loading features from cached file {cached_features_file} [took %.3f s]"""   ,    time.time() - start	)

           if self.dataset is None or self.examples is None:
              logger.warning(
                  f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
                  ' future run'	)
        else:
           if mode == Split.dev:
              __lowerCAmelCase				      =      self.processor.get_dev_examples(args.data_dir	)
           else:
              __lowerCAmelCase				      =      self.processor.get_train_examples(args.data_dir	)

           __lowerCAmelCase      ,      __lowerCAmelCase				      =      squad_convert_examples_to_features(
               examples=self.examples   ,    tokenizer=lowerCAmelCase_   ,    max_seq_length=args.max_seq_length   ,    doc_stride=args.doc_stride   ,    max_query_length=args.max_query_length   ,    is_training=mode == Split.train   ,    threads=args.threads   ,    return_dataset=lowerCAmelCase_   ,    )

           __lowerCAmelCase				      =      time.time()
           torch.save(
               {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}   ,    lowerCAmelCase_   ,    )
           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
           logger.info(
               f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""	)






  def __len__(							self					:						Tuple	)				->		List[str]:
     return len(self.features	)






  def __getitem__(							self					:						Dict   ,    lowerCAmelCase_					:						Optional[int]	)				->		Dict[str, torch.Tensor]:
     # Convert to Tensors and build dataset
     __lowerCAmelCase				      =      self.features[i]

     __lowerCAmelCase				      =      torch.tensor(feature.input_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.attention_mask   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.token_type_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.cls_index   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.p_mask   ,    dtype=torch.float	)
     __lowerCAmelCase				      =      torch.tensor(feature.is_impossible   ,    dtype=torch.float	)

     __lowerCAmelCase				      =      {
         'input_ids': input_ids,
         'attention_mask': attention_mask,
         'token_type_ids': token_type_ids,
     }

     if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
        del inputs["token_type_ids"]

     if self.args.model_type in ["xlnet", "xlm"]:
        inputs.update({'cls_index': cls_index, 'p_mask': p_mask}	)
        if self.args.version_2_with_negative:
           inputs.update({'is_impossible': is_impossible}	)
        if self.is_language_sensitive:
           inputs.update({'langs': (torch.ones(input_ids.shape   ,    dtype=torch.intaa	) * self.args.lang_id)}	)

     if self.mode == Split.train:
        __lowerCAmelCase				      =      torch.tensor(feature.start_position   ,    dtype=torch.long	)
        __lowerCAmelCase				      =      torch.tensor(feature.end_position   ,    dtype=torch.long	)
        inputs.update({'start_positions': start_positions, 'end_positions': end_positions}	)

     return inputs


import copy
import os
from typing import Union

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


SCREAMING_SNAKE_CASE			:						List[Any]				  =		logging.get_logger(__name__)

SCREAMING_SNAKE_CASE			:						Optional[int]				  =		{
    """Salesforce/blip-vqa-base""": """https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json""",
    """Salesforce/blip-vqa-capfit-large""": (
        """https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"""
    ),
    """Salesforce/blip-image-captioning-base""": (
        """https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"""
    ),
    """Salesforce/blip-image-captioning-large""": (
        """https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"""
    ),
    """Salesforce/blip-itm-base-coco""": """https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json""",
    """Salesforce/blip-itm-large-coco""": """https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json""",
    """Salesforce/blip-itm-base-flikr""": """https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json""",
    """Salesforce/blip-itm-large-flikr""": (
        """https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"""
    ),
}
class  A_			(							a_			):
  _SCREAMING_SNAKE_CASE     					=      """blip_text_model"""

  def __init__(		self			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   str=3_05_24  ,				__SCREAMING_SNAKE_CASE			:   Any=7_68  ,				__SCREAMING_SNAKE_CASE			:   List[Any]=7_68  ,				__SCREAMING_SNAKE_CASE			:   Tuple=30_72  ,				__SCREAMING_SNAKE_CASE			:   Any=7_68  ,				__SCREAMING_SNAKE_CASE			:   Tuple=12  ,				__SCREAMING_SNAKE_CASE			:   Dict=8  ,				__SCREAMING_SNAKE_CASE			:   int=5_12  ,				__SCREAMING_SNAKE_CASE			:   List[Any]="gelu"  ,				__SCREAMING_SNAKE_CASE			:   int=1E-12  ,				__SCREAMING_SNAKE_CASE			:   Tuple=0.0  ,				__SCREAMING_SNAKE_CASE			:   Tuple=0.0  ,				__SCREAMING_SNAKE_CASE			:   Dict=0.02  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=3_05_22  ,				__SCREAMING_SNAKE_CASE			:   Any=2  ,				__SCREAMING_SNAKE_CASE			:   List[str]=0  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=1_02  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=True  ,				__SCREAMING_SNAKE_CASE			:   Dict=True  ,				**__SCREAMING_SNAKE_CASE			:   str  ,				):
   super().__init__(
       pad_token_id=__SCREAMING_SNAKE_CASE  ,				bos_token_id=__SCREAMING_SNAKE_CASE  ,				eos_token_id=__SCREAMING_SNAKE_CASE  ,				sep_token_id=__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE  ,				)

   __a							=	vocab_size
   __a							=	hidden_size
   __a							=	encoder_hidden_size
   __a							=	intermediate_size
   __a							=	projection_dim
   __a							=	hidden_dropout_prob
   __a							=	num_hidden_layers
   __a							=	num_attention_heads
   __a							=	max_position_embeddings
   __a							=	layer_norm_eps
   __a							=	hidden_act
   __a							=	initializer_range
   __a							=	attention_probs_dropout_prob
   __a							=	is_decoder
   __a							=	use_cache

  @classmethod
  def 		_UpperCAmelCase (		cls			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   Union[str, os.PathLike]  ,				**__SCREAMING_SNAKE_CASE			:   int							):
   cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE							)

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

   # get the text config dict if we are loading from BlipConfig
   if config_dict.get("model_type"							) == "blip":
    __a							=	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(__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)
class  A_			(							a_			):
  _SCREAMING_SNAKE_CASE     					=      """blip_vision_model"""

  def __init__(		self			:   Optional[int]  ,				__SCREAMING_SNAKE_CASE			:   str=7_68  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]=30_72  ,				__SCREAMING_SNAKE_CASE			:   List[Any]=5_12  ,				__SCREAMING_SNAKE_CASE			:   int=12  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]=12  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=3_84  ,				__SCREAMING_SNAKE_CASE			:   str=16  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]="gelu"  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=1E-5  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]=0.0  ,				__SCREAMING_SNAKE_CASE			:   List[Any]=1E-10  ,				**__SCREAMING_SNAKE_CASE			:   List[str]  ,				):
   super().__init__(**__SCREAMING_SNAKE_CASE							)

   __a							=	hidden_size
   __a							=	intermediate_size
   __a							=	projection_dim
   __a							=	num_hidden_layers
   __a							=	num_attention_heads
   __a							=	patch_size
   __a							=	image_size
   __a							=	initializer_range
   __a							=	attention_dropout
   __a							=	layer_norm_eps
   __a							=	hidden_act

  @classmethod
  def 		_UpperCAmelCase (		cls			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Union[str, os.PathLike]  ,				**__SCREAMING_SNAKE_CASE			:   str							):
   cls._set_token_in_kwargs(__SCREAMING_SNAKE_CASE							)

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

   # get the vision config dict if we are loading from BlipConfig
   if config_dict.get("model_type"							) == "blip":
    __a							=	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(__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)
class  A_			(							a_			):
  _SCREAMING_SNAKE_CASE     					=      """blip"""
  _SCREAMING_SNAKE_CASE     					=      True

  def __init__(		self			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=None  ,				__SCREAMING_SNAKE_CASE			:   Any=None  ,				__SCREAMING_SNAKE_CASE			:   int=5_12  ,				__SCREAMING_SNAKE_CASE			:   List[Any]=2.65_92  ,				__SCREAMING_SNAKE_CASE			:   Any=2_56  ,				**__SCREAMING_SNAKE_CASE			:   Any  ,				):
   super().__init__(**__SCREAMING_SNAKE_CASE							)

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

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

   __a							=	BlipTextConfig(**__SCREAMING_SNAKE_CASE							)
   __a							=	BlipVisionConfig(**__SCREAMING_SNAKE_CASE							)

   __a							=	self.vision_config.hidden_size

   __a							=	projection_dim
   __a							=	logit_scale_init_value
   __a							=	1.0
   __a							=	0.02
   __a							=	image_text_hidden_size

  @classmethod
  def 		_UpperCAmelCase (		cls			:   Any  ,				__SCREAMING_SNAKE_CASE			:   BlipTextConfig  ,				__SCREAMING_SNAKE_CASE			:   BlipVisionConfig  ,				**__SCREAMING_SNAKE_CASE			:   List[Any]							):
   return cls(text_config=text_config.to_dict()  ,				vision_config=vision_config.to_dict()  ,				**__SCREAMING_SNAKE_CASE							)

  def 		_UpperCAmelCase (		self			:   Union[str, Any]							):
   __a							=	copy.deepcopy(self.__dict__							)
   __a							=	self.text_config.to_dict()
   __a							=	self.vision_config.to_dict()
   __a							=	self.__class__.model_type
   return output


