

'''simple docstring'''
import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
    from ...processing_utils import ProcessorMixin
    from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_snake_case         =  logging.get_logger(__name__)

_snake_case         =  {
    'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json',
    'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json',
    'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json',
}


class        a__  (							__snake_case  ):






   """simple docstring"""




   _SCREAMING_SNAKE_CASE   :					str     	=							'owlvit_text_model'


   def __init__(			self      ,    _UpperCamelCase=49408      ,    _UpperCamelCase=512      ,    _UpperCamelCase=2048      ,    _UpperCamelCase=12      ,    _UpperCamelCase=8      ,    _UpperCamelCase=16      ,    _UpperCamelCase="quick_gelu"      ,    _UpperCamelCase=1E-5      ,    _UpperCamelCase=0.0      ,    _UpperCamelCase=0.0_2      ,    _UpperCamelCase=1.0      ,    _UpperCamelCase=0      ,    _UpperCamelCase=49406      ,    _UpperCamelCase=49407      ,    **_UpperCamelCase      ,    ):





      """simple docstring"""





      super().__init__(pad_token_id=_UpperCamelCase      ,    bos_token_id=_UpperCamelCase      ,    eos_token_id=_UpperCamelCase      ,    **_UpperCamelCase  )

      _lowercase      :				int      					=       vocab_size
      _lowercase      :				Optional[Any]      					=       hidden_size
      _lowercase      :				Optional[int]      					=       intermediate_size
      _lowercase      :				List[str]      					=       num_hidden_layers
      _lowercase      :				Tuple      					=       num_attention_heads
      _lowercase      :				int      					=       max_position_embeddings
      _lowercase      :				Dict      					=       hidden_act
      _lowercase      :				Tuple      					=       layer_norm_eps
      _lowercase      :				Union[str, Any]      					=       attention_dropout
      _lowercase      :				Dict      					=       initializer_range
      _lowercase      :				Union[str, Any]      					=       initializer_factor






   @classmethod
   def 						_lowerCamelCase       (			cls      ,    _UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      cls._set_token_in_kwargs(_UpperCamelCase  )

      _lowercase					,				_lowercase      :				Any      					=       cls.get_config_dict(_UpperCamelCase      ,    **_UpperCamelCase  )

      # get the text config dict if we are loading from OwlViTConfig
      if config_dict.get("model_type"  ) == "owlvit":
         _lowercase      :				List[str]      					=       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(_UpperCamelCase      ,    **_UpperCamelCase  )




class        a__  (							__snake_case  ):






   """simple docstring"""




   _SCREAMING_SNAKE_CASE   :					str     	=							'owlvit_vision_model'


   def __init__(			self      ,    _UpperCamelCase=768      ,    _UpperCamelCase=3072      ,    _UpperCamelCase=12      ,    _UpperCamelCase=12      ,    _UpperCamelCase=3      ,    _UpperCamelCase=768      ,    _UpperCamelCase=32      ,    _UpperCamelCase="quick_gelu"      ,    _UpperCamelCase=1E-5      ,    _UpperCamelCase=0.0      ,    _UpperCamelCase=0.0_2      ,    _UpperCamelCase=1.0      ,    **_UpperCamelCase      ,    ):





      """simple docstring"""





      super().__init__(**_UpperCamelCase  )

      _lowercase      :				List[Any]      					=       hidden_size
      _lowercase      :				List[Any]      					=       intermediate_size
      _lowercase      :				List[str]      					=       num_hidden_layers
      _lowercase      :				Union[str, Any]      					=       num_attention_heads
      _lowercase      :				Tuple      					=       num_channels
      _lowercase      :				Optional[int]      					=       image_size
      _lowercase      :				List[str]      					=       patch_size
      _lowercase      :				List[Any]      					=       hidden_act
      _lowercase      :				List[str]      					=       layer_norm_eps
      _lowercase      :				List[str]      					=       attention_dropout
      _lowercase      :				List[Any]      					=       initializer_range
      _lowercase      :				List[Any]      					=       initializer_factor






   @classmethod
   def 						_lowerCamelCase       (			cls      ,    _UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      cls._set_token_in_kwargs(_UpperCamelCase  )

      _lowercase					,				_lowercase      :				Dict      					=       cls.get_config_dict(_UpperCamelCase      ,    **_UpperCamelCase  )

      # get the vision config dict if we are loading from OwlViTConfig
      if config_dict.get("model_type"  ) == "owlvit":
         _lowercase      :				List[Any]      					=       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(_UpperCamelCase      ,    **_UpperCamelCase  )




class        a__  (							__snake_case  ):






   """simple docstring"""




   _SCREAMING_SNAKE_CASE   :					int     	=							'owlvit'
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							True


   def __init__(			self      ,    _UpperCamelCase=None      ,    _UpperCamelCase=None      ,    _UpperCamelCase=512      ,    _UpperCamelCase=2.6_5_9_2      ,    _UpperCamelCase=True      ,    **_UpperCamelCase      ,    ):





      """simple docstring"""





      super().__init__(**_UpperCamelCase  )

      if text_config is None:
         _lowercase      :				Optional[Any]      					=       {}
         logger.info("text_config is None. Initializing the OwlViTTextConfig with default values."  )

      if vision_config is None:
         _lowercase      :				Tuple      					=       {}
         logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values."  )

      _lowercase      :				Dict      					=       OwlViTTextConfig(**_UpperCamelCase  )
      _lowercase      :				List[str]      					=       OwlViTVisionConfig(**_UpperCamelCase  )

      _lowercase      :				str      					=       projection_dim
      _lowercase      :				List[Any]      					=       logit_scale_init_value
      _lowercase      :				str      					=       return_dict
      _lowercase      :				Any      					=       1.0


   @classmethod
   def 						_lowerCamelCase       (			cls      ,    _UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      cls._set_token_in_kwargs(_UpperCamelCase  )

      _lowercase					,				_lowercase      :				Optional[Any]      					=       cls.get_config_dict(_UpperCamelCase      ,    **_UpperCamelCase  )

      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(_UpperCamelCase      ,    **_UpperCamelCase  )


   @classmethod
   def 						_lowerCamelCase       (			cls      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				str      					=       {}
      _lowercase      :				Any      					=       text_config
      _lowercase      :				List[str]      					=       vision_config

      return cls.from_dict(_UpperCamelCase      ,    **_UpperCamelCase  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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




class        a__  (							__snake_case  ):






   """simple docstring"""




   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return OrderedDict(
          [
              ("input_ids", {0: "batch", 1: "sequence"}),
              ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
              ("attention_mask", {0: "batch", 1: "sequence"}),
          ]  )


   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return OrderedDict(
          [
              ("logits_per_image", {0: "batch"}),
              ("logits_per_text", {0: "batch"}),
              ("text_embeds", {0: "batch"}),
              ("image_embeds", {0: "batch"}),
          ]  )


   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return 1E-4


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase = -1      ,    _UpperCamelCase = -1      ,    _UpperCamelCase = None      ,    ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       super().generate_dummy_inputs(
          processor.tokenizer      ,    batch_size=_UpperCamelCase      ,    seq_length=_UpperCamelCase      ,    framework=_UpperCamelCase  )
      _lowercase      :				Optional[int]      					=       super().generate_dummy_inputs(
          processor.image_processor      ,    batch_size=_UpperCamelCase      ,    framework=_UpperCamelCase  )
      return {**text_input_dict, **image_input_dict}






   @property
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return 14









'''simple docstring'''
import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class        a__  (							lowerCamelCase_  ,				lowerCamelCase_  ,				unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							IFImgaImgSuperResolutionPipeline
   _SCREAMING_SNAKE_CASE   :					int     	=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}  )
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							PipelineTesterMixin.required_optional_params - {'latents'}


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      return self._get_superresolution_dummy_components()


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase=0  ):





      """simple docstring"""





      if str(_UpperCamelCase  ).startswith("mps"  ):
         _lowercase      :				Tuple      					=       torch.manual_seed(_UpperCamelCase  )
      else:
         _lowercase      :				int      					=       torch.Generator(device=_UpperCamelCase  ).manual_seed(_UpperCamelCase  )

      _lowercase      :				List[Any]      					=       floats_tensor((1, 3, 32, 32)      ,    rng=random.Random(_UpperCamelCase  )  ).to(_UpperCamelCase  )
      _lowercase      :				Optional[int]      					=       floats_tensor((1, 3, 16, 16)      ,    rng=random.Random(_UpperCamelCase  )  ).to(_UpperCamelCase  )

      _lowercase      :				List[str]      					=       {
          "prompt": "A painting of a squirrel eating a burger",
          "image": image,
          "original_image": original_image,
          "generator": generator,
          "num_inference_steps": 2,
          "output_type": "numpy",
      }

      return inputs


   @unittest.skipIf(
       torch_device != "cuda" or not is_xformers_available()      ,    reason="XFormers attention is only available with CUDA and `xformers` installed"      ,    )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_save_load_optional_components()


   @unittest.skipIf(torch_device != "cuda"      ,    reason="float16 requires CUDA"  )
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      super().test_save_load_floataa(expected_max_diff=1E-1  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_attention_slicing_forward_pass(expected_max_diff=1E-2  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_save_load_local()






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      self._test_inference_batch_single_identical(
          expected_max_diff=1E-2      ,    )






