






"""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


A_      	=     logging.get_logger(__name__)

A_      	=     {
    "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     __lowerCAmelCase (      A_							):







  '''simple docstring'''


  __lowerCamelCase							:     List[str]  						=      "owlvit_text_model"
  def __init__(   self:		Tuple					,      UpperCamelCase_:		str=4_9408					,      UpperCamelCase_:		Union[str, Any]=512					,      UpperCamelCase_:		List[str]=2048					,      UpperCamelCase_:		Dict=12					,      UpperCamelCase_:		Tuple=8					,      UpperCamelCase_:		List[Any]=16					,      UpperCamelCase_:		str="quick_gelu"					,      UpperCamelCase_:		int=1e-5					,      UpperCamelCase_:		str=0.0					,      UpperCamelCase_:		List[str]=0.02					,      UpperCamelCase_:		str=1.0					,      UpperCamelCase_:		Tuple=0					,      UpperCamelCase_:		List[Any]=4_9406					,      UpperCamelCase_:		Union[str, Any]=4_9407					,      **UpperCamelCase_:		str					,      ):
     super().__init__(pad_token_id=UpperCamelCase_					,      bos_token_id=UpperCamelCase_					,      eos_token_id=UpperCamelCase_					,      **UpperCamelCase_       )

     UpperCamelCase_			     =vocab_size
     UpperCamelCase_			     =hidden_size
     UpperCamelCase_			     =intermediate_size
     UpperCamelCase_			     =num_hidden_layers
     UpperCamelCase_			     =num_attention_heads
     UpperCamelCase_			     =max_position_embeddings
     UpperCamelCase_			     =hidden_act
     UpperCamelCase_			     =layer_norm_eps
     UpperCamelCase_			     =attention_dropout
     UpperCamelCase_			     =initializer_range
     UpperCamelCase_			     =initializer_factor





  @classmethod
  def        UpperCamelCase__ (   cls:		Optional[int]					,      UpperCamelCase_:		List[Any]					,      **UpperCamelCase_:		Union[str, Any]       ):
     cls._set_token_in_kwargs(UpperCamelCase_       )

     UpperCamelCase_			     =cls.get_config_dict(UpperCamelCase_					,      **UpperCamelCase_       )

     # get the text config dict if we are loading from OwlViTConfig
     if config_dict.get("model_type"       ) == "owlvit":
        UpperCamelCase_			     =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     __lowerCAmelCase (      A_							):







  '''simple docstring'''


  __lowerCamelCase							:     str  						=      "owlvit_vision_model"
  def __init__(   self:		Any					,      UpperCamelCase_:		Tuple=768					,      UpperCamelCase_:		Optional[int]=3072					,      UpperCamelCase_:		int=12					,      UpperCamelCase_:		Optional[Any]=12					,      UpperCamelCase_:		Tuple=3					,      UpperCamelCase_:		List[str]=768					,      UpperCamelCase_:		Optional[int]=32					,      UpperCamelCase_:		List[Any]="quick_gelu"					,      UpperCamelCase_:		Optional[int]=1e-5					,      UpperCamelCase_:		List[str]=0.0					,      UpperCamelCase_:		List[str]=0.02					,      UpperCamelCase_:		Union[str, Any]=1.0					,      **UpperCamelCase_:		List[Any]					,      ):
     super().__init__(**UpperCamelCase_       )

     UpperCamelCase_			     =hidden_size
     UpperCamelCase_			     =intermediate_size
     UpperCamelCase_			     =num_hidden_layers
     UpperCamelCase_			     =num_attention_heads
     UpperCamelCase_			     =num_channels
     UpperCamelCase_			     =image_size
     UpperCamelCase_			     =patch_size
     UpperCamelCase_			     =hidden_act
     UpperCamelCase_			     =layer_norm_eps
     UpperCamelCase_			     =attention_dropout
     UpperCamelCase_			     =initializer_range
     UpperCamelCase_			     =initializer_factor





  @classmethod
  def        UpperCamelCase__ (   cls:		str					,      UpperCamelCase_:		Dict					,      **UpperCamelCase_:		Tuple       ):
     cls._set_token_in_kwargs(UpperCamelCase_       )

     UpperCamelCase_			     =cls.get_config_dict(UpperCamelCase_					,      **UpperCamelCase_       )

     # get the vision config dict if we are loading from OwlViTConfig
     if config_dict.get("model_type"       ) == "owlvit":
        UpperCamelCase_			     =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     __lowerCAmelCase (      A_							):







  '''simple docstring'''


  __lowerCamelCase							:     Optional[int]  						=      "owlvit"
  __lowerCamelCase							:     Any  						=      True
  def __init__(   self:		List[Any]					,      UpperCamelCase_:		Optional[Any]=None					,      UpperCamelCase_:		Dict=None					,      UpperCamelCase_:		str=512					,      UpperCamelCase_:		str=2.6592					,      UpperCamelCase_:		List[str]=True					,      **UpperCamelCase_:		int					,      ):
     super().__init__(**UpperCamelCase_       )

     if text_config is None:
        UpperCamelCase_			     ={}
        logger.info("text_config is None. Initializing the OwlViTTextConfig with default values."       )

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

     UpperCamelCase_			     =OwlViTTextConfig(**UpperCamelCase_       )
     UpperCamelCase_			     =OwlViTVisionConfig(**UpperCamelCase_       )

     UpperCamelCase_			     =projection_dim
     UpperCamelCase_			     =logit_scale_init_value
     UpperCamelCase_			     =return_dict
     UpperCamelCase_			     =1.0
  @classmethod
  def        UpperCamelCase__ (   cls:		str					,      UpperCamelCase_:		str					,      **UpperCamelCase_:		Union[str, Any]       ):
     cls._set_token_in_kwargs(UpperCamelCase_       )

     UpperCamelCase_			     =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        UpperCamelCase__ (   cls:		List[Any]					,      UpperCamelCase_:		Any					,      UpperCamelCase_:		List[Any]					,      **UpperCamelCase_:		Union[str, Any]       ):
     UpperCamelCase_			     ={}
     UpperCamelCase_			     =text_config
     UpperCamelCase_			     =vision_config

     return cls.from_dict(UpperCamelCase_					,      **UpperCamelCase_       )





  def        UpperCamelCase__ (   self:		str       ):
     UpperCamelCase_			     =copy.deepcopy(self.__dict__       )
     UpperCamelCase_			     =self.text_config.to_dict()
     UpperCamelCase_			     =self.vision_config.to_dict()
     UpperCamelCase_			     =self.__class__.model_type
     return output




class     __lowerCAmelCase (      A_							):







  '''simple docstring'''


  @property
  def        UpperCamelCase__ (   self:		Optional[int]       ):
     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        UpperCamelCase__ (   self:		Any       ):
     return OrderedDict(
         [
             ("logits_per_image", {0: "batch"}),
             ("logits_per_text", {0: "batch"}),
             ("text_embeds", {0: "batch"}),
             ("image_embeds", {0: "batch"}),
         ]       )
  @property
  def        UpperCamelCase__ (   self:		int       ):
     return 1e-4
  def        UpperCamelCase__ (   self:		Optional[Any]					,      UpperCamelCase_:		Any					,      UpperCamelCase_:		Union[str, Any] = -1					,      UpperCamelCase_:		str = -1					,      UpperCamelCase_:		Union[str, Any] = None					,      ):
     UpperCamelCase_			     =super().generate_dummy_inputs(
         processor.tokenizer					,      batch_size=UpperCamelCase_					,      seq_length=UpperCamelCase_					,      framework=UpperCamelCase_       )
     UpperCamelCase_			     =super().generate_dummy_inputs(
         processor.image_processor					,      batch_size=UpperCamelCase_					,      framework=UpperCamelCase_       )
     return {**text_input_dict, **image_input_dict}





  @property
  def        UpperCamelCase__ (   self:		List[str]       ):
     return 14




"""simple docstring"""
import mpmath  # for roots of unity
import numpy as np




class 	lowercase__				:





   def __init__(							self      ,   SCREAMING_SNAKE_CASE=None      ,   SCREAMING_SNAKE_CASE=None)  ->  Tuple:
      # Input as list
      _lowerCamelCase	:					Any   =		list(poly_a or [0])[:]
      _lowerCamelCase	:					Optional[Any]   =		list(poly_b or [0])[:]

      # Remove leading zero coefficients
      while self.polyA[-1] == 0:
         self.polyA.pop()
      _lowerCamelCase	:					int   =		len(self.polyA)

      while self.polyB[-1] == 0:
         self.polyB.pop()
      _lowerCamelCase	:					Union[str, Any]   =		len(self.polyB)

      # Add 0 to make lengths equal a power of 2
      _lowerCamelCase	:					List[Any]   =		int(
          2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1)))

      while len(self.polyA) < self.c_max_length:
         self.polyA.append(0)
      while len(self.polyB) < self.c_max_length:
         self.polyB.append(0)
      # A complex root used for the fourier transform
      _lowerCamelCase	:					Optional[Any]   =		complex(mpmath.root(x=1      ,   n=self.c_max_length      ,   k=1))

      # The product
      _lowerCamelCase	:					int   =		self.__multiply()





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE)  ->  List[str]:
      _lowerCamelCase	:					Dict   =		[[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB]
      # Corner case
      if len(SCREAMING_SNAKE_CASE) <= 1:
         return dft[0]
      #
      _lowerCamelCase	:					str   =		self.c_max_length // 2
      while next_ncol > 0:
         _lowerCamelCase	:					Dict   =		[[] for i in range(SCREAMING_SNAKE_CASE)]
         _lowerCamelCase	:					Tuple   =		self.root**next_ncol

         # First half of next step
         _lowerCamelCase	:					int   =		1
         for j in range(self.c_max_length // (next_ncol * 2)):
            for i in range(SCREAMING_SNAKE_CASE):
               new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
            current_root *= root
         # Second half of next step
         _lowerCamelCase	:					Optional[int]   =		1
         for j in range(self.c_max_length // (next_ncol * 2)):
            for i in range(SCREAMING_SNAKE_CASE):
               new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
            current_root *= root
         # Update
         _lowerCamelCase	:					Union[str, Any]   =		new_dft
         _lowerCamelCase	:					List[str]   =		next_ncol // 2
      return dft[0]





   def 		UpperCamelCase_  (							self)  ->  str:
      _lowerCamelCase	:					Optional[Any]   =		self.__dft("""A""")
      _lowerCamelCase	:					List[str]   =		self.__dft("""B""")
      _lowerCamelCase	:					List[Any]   =		[[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
      del dft_a
      del dft_b

      # Corner Case
      if len(inverce_c[0]) <= 1:
         return inverce_c[0]
      # Inverse DFT
      _lowerCamelCase	:					List[str]   =		2
      while next_ncol <= self.c_max_length:
         _lowerCamelCase	:					Any   =		[[] for i in range(SCREAMING_SNAKE_CASE)]
         _lowerCamelCase	:					List[Any]   =		self.root ** (next_ncol // 2)
         _lowerCamelCase	:					str   =		1
         # First half of next step
         for j in range(self.c_max_length // next_ncol):
            for i in range(next_ncol // 2):
               # Even positions
               new_inverse_c[i].append(
                   (
                       inverce_c[i][j]
                       + inverce_c[i][j + self.c_max_length // next_ncol]
                   )
                   / 2)
               # Odd positions
               new_inverse_c[i + next_ncol // 2].append(
                   (
                       inverce_c[i][j]
                       - inverce_c[i][j + self.c_max_length // next_ncol]
                   )
                   / (2 * current_root))
            current_root *= root
         # Update
         _lowerCamelCase	:					Any   =		new_inverse_c
         next_ncol *= 2
      # Unpack
      _lowerCamelCase	:					Optional[Any]   =		[round(x[0].real      ,   8) + round(x[0].imag      ,   8) * 1j for x in inverce_c]

      # Remove leading 0's
      while inverce_c[-1] == 0:
         inverce_c.pop()
      return inverce_c





   def __str__(							self)  ->  Any:
      _lowerCamelCase	:					Dict   =		"""A = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A]))
      _lowerCamelCase	:					List[Any]   =		"""B = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B]))
      _lowerCamelCase	:					int   =		"""A*B = """ + """ + """.join(
          F'{coef}*x^{i}' for coef, i in enumerate(self.product))

      return F'{a}\n{b}\n{c}'


# Unit tests
if __name__ == "__main__":
 import doctest

 doctest.testmod()

