

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


_lowerCAmelCase         =						logging.get_logger(__name__)

_lowerCAmelCase         =						{
    "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   _SCREAMING_SNAKE_CASE   (   __a     ):
 __SCREAMING_SNAKE_CASE					:Tuple      	=					"""owlvit_text_model"""



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

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



 @classmethod
 def 			snake_case__  (   cls		:   List[str]			,				a__		:   Union[str, os.PathLike]			,				**a__		:   Optional[int]      ):
      cls._set_token_in_kwargs(a__      )

      __magic_name__       ,  __magic_name__						       =    cls.get_config_dict(a__			,				**a__      )

      # get the text config dict if we are loading from OwlViTConfig
      if config_dict.get('''model_type'''      ) == "owlvit":
           __magic_name__						       =    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   _SCREAMING_SNAKE_CASE   (   __a     ):
 __SCREAMING_SNAKE_CASE					:int      	=					"""owlvit_vision_model"""



 def __init__(   self		:   Tuple			,				a__		:   Any=768			,				a__		:   List[Any]=3072			,				a__		:   Dict=12			,				a__		:   Tuple=12			,				a__		:   Any=3			,				a__		:   Optional[Any]=768			,				a__		:   List[str]=32			,				a__		:   Dict="quick_gelu"			,				a__		:   Any=1E-5			,				a__		:   List[str]=0.0			,				a__		:   Optional[Any]=0.02			,				a__		:   str=1.0			,				**a__		:   List[Any]			,				):
      super().__init__(**a__      )

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



 @classmethod
 def 			snake_case__  (   cls		:   Any			,				a__		:   Union[str, os.PathLike]			,				**a__		:   str      ):
      cls._set_token_in_kwargs(a__      )

      __magic_name__       ,  __magic_name__						       =    cls.get_config_dict(a__			,				**a__      )

      # get the vision config dict if we are loading from OwlViTConfig
      if config_dict.get('''model_type'''      ) == "owlvit":
           __magic_name__						       =    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(a__			,				**a__      )






class   _SCREAMING_SNAKE_CASE   (   __a     ):
 __SCREAMING_SNAKE_CASE					:str      	=					"""owlvit"""
 __SCREAMING_SNAKE_CASE					:Union[str, Any]      	=					True



 def __init__(   self		:   Optional[Any]			,				a__		:   Tuple=None			,				a__		:   str=None			,				a__		:   List[Any]=512			,				a__		:   List[str]=2.6_592			,				a__		:   List[Any]=True			,				**a__		:   List[str]			,				):
      super().__init__(**a__      )

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

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

      __magic_name__						       =    OwlViTTextConfig(**a__      )
      __magic_name__						       =    OwlViTVisionConfig(**a__      )

      __magic_name__						       =    projection_dim
      __magic_name__						       =    logit_scale_init_value
      __magic_name__						       =    return_dict
      __magic_name__						       =    1.0



 @classmethod
 def 			snake_case__  (   cls		:   Union[str, Any]			,				a__		:   Union[str, os.PathLike]			,				**a__		:   str      ):
      cls._set_token_in_kwargs(a__      )

      __magic_name__       ,  __magic_name__						       =    cls.get_config_dict(a__			,				**a__      )

      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__      )



 @classmethod
 def 			snake_case__  (   cls		:   str			,				a__		:   Dict			,				a__		:   Dict			,				**a__		:   Dict      ):
      __magic_name__						       =    {}
      __magic_name__						       =    text_config
      __magic_name__						       =    vision_config

      return cls.from_dict(a__			,				**a__      )



 def 			snake_case__  (   self		:   Optional[Any]      ):
      __magic_name__						       =    copy.deepcopy(self.__dict__      )
      __magic_name__						       =    self.text_config.to_dict()
      __magic_name__						       =    self.vision_config.to_dict()
      __magic_name__						       =    self.__class__.model_type
      return output






class   _SCREAMING_SNAKE_CASE   (   __a     ):



 @property
 def 			snake_case__  (   self		:   Dict      ):
      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 			snake_case__  (   self		:   Dict      ):
      return OrderedDict(
          [
              ('''logits_per_image''', {0: '''batch'''}),
              ('''logits_per_text''', {0: '''batch'''}),
              ('''text_embeds''', {0: '''batch'''}),
              ('''image_embeds''', {0: '''batch'''}),
          ]      )



 @property
 def 			snake_case__  (   self		:   Union[str, Any]      ):
      return 1E-4



 def 			snake_case__  (   self		:   str			,				a__		:   "ProcessorMixin"			,				a__		:   int = -1			,				a__		:   int = -1			,				a__		:   Optional["TensorType"] = None			,				):
      __magic_name__						       =    super().generate_dummy_inputs(
          processor.tokenizer			,				batch_size=a__			,				seq_length=a__			,				framework=a__      )
      __magic_name__						       =    super().generate_dummy_inputs(
          processor.image_processor			,				batch_size=a__			,				framework=a__      )
      return {**text_input_dict, **image_input_dict}



 @property
 def 			snake_case__  (   self		:   Any      ):
      return 14









'''simple docstring'''




import re

from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P


# Sentinels
_lowerCAmelCase         =						object()

# For specifying empty leaf dict `{}`
_lowerCAmelCase         =						object()




def 						UpperCamelCase	(			a		,						a			)				->     Union[str, Any]:






     '''simple docstring'''
     __magic_name__						       =    tuple((re.compile(x + '''$'''			) for x in qs)			)
     for i in range(len(a			) - len(a			) + 1			):
          __magic_name__						       =    [x.match(a			) for x, y in zip(a		,						ks[i:]			)]
          if matches and all(a			):
               return True
     return False




def 						UpperCamelCase	(			a			)				->     Tuple:






     '''simple docstring'''
     def replace(a		,						a			):
          for rule, replacement in rules:
               if _match(a		,						a			):
                    return replacement
          return val

     return replace




def 						UpperCamelCase	(			)				->     Union[str, Any]:






     '''simple docstring'''
     return [
         # embeddings
         (("transformer", "wpe", "embedding"), P('''mp'''		,						a			)),
         (("transformer", "wte", "embedding"), P('''mp'''		,						a			)),
         # atention
         (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a		,						'''mp'''			)),
         (("attention", "out_proj", "kernel"), P('''mp'''		,						a			)),
         (("attention", "out_proj", "bias"), None),
         # mlp
         (("mlp", "c_fc", "kernel"), P(a		,						'''mp'''			)),
         (("mlp", "c_fc", "bias"), P('''mp'''			)),
         (("mlp", "c_proj", "kernel"), P('''mp'''		,						a			)),
         (("mlp", "c_proj", "bias"), None),
         # layer norms
         ((r"ln_\d+", "bias"), None),
         ((r"\d+", r"ln_\d+", "scale"), None),
         (("ln_f", "bias"), None),
         (("ln_f", "scale"), None),
     ]




def 						UpperCamelCase	(			a			)				->     str:






     '''simple docstring'''
     __magic_name__						       =    _get_partition_rules()
     __magic_name__						       =    _replacement_rules(a			)
     __magic_name__						       =    {k: _unmatched for k in flatten_dict(a			)}
     __magic_name__						       =    {k: replace(a		,						a			) for k, v in initd.items()}
     assert _unmatched not in result.values(), "Incomplete partition spec."
     return freeze(unflatten_dict(a			)			)






