


'''simple docstring'''


import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
     import bitsandbytes as bnb
     import torch
     import torch.nn as nn

     from ..pytorch_utils import ConvaD

if is_accelerate_available():
     from accelerate import init_empty_weights
     from accelerate.utils import find_tied_parameters

__magic_name__			=      logging.get_logger(__name__)




def      lowerCamelCase					(      lowerCamelCase  :      Tuple							,						lowerCamelCase  :      Optional[int]							,						lowerCamelCase  :      int							,						lowerCamelCase  :      Optional[Any]=None							,						lowerCamelCase  :      Optional[Any]=None):
      # Recurse if needed
      if "." in tensor_name:
            A_						:  Union[str, Any]          =				tensor_name.split(""".""")
            for split in splits[:-1]:
                  A_						:  List[str]          =				getattr(lowerCamelCase							,						lowerCamelCase)
                  if new_module is None:
                        raise ValueError(F'{module} has no attribute {split}.')
                  A_						:  Any          =				new_module
            A_						:  Tuple          =				splits[-1]

      if tensor_name not in module._parameters and tensor_name not in module._buffers:
            raise ValueError(F'{module} does not have a parameter or a buffer named {tensor_name}.')
      A_						:  Union[str, Any]          =				tensor_name in module._buffers
      A_						:  str          =				getattr(lowerCamelCase							,						lowerCamelCase)

      if old_value.device == torch.device("""meta""") and device not in ["meta", torch.device("""meta""")] and value is None:
            raise ValueError(F'{tensor_name} is on the meta device, we need a `value` to put in on {device}.')

      A_						:  int          =				False
      A_						:  Any          =				False
      if is_buffer or not is_bitsandbytes_available():
            A_						:  Tuple          =				False
            A_						:  str          =				False
      else:
            A_						:  Any          =				hasattr(bnb.nn							,						"""Params4bit""") and isinstance(module._parameters[tensor_name]							,						bnb.nn.Paramsabit)
            A_						:  Dict          =				isinstance(module._parameters[tensor_name]							,						bnb.nn.IntaParams)

      if is_abit or is_abit:
            A_						:  Optional[Any]          =				module._parameters[tensor_name]
            if param.device.type != "cuda":
                  if value is None:
                        A_						:  int          =				old_value.to(lowerCamelCase)
                  elif isinstance(lowerCamelCase							,						torch.Tensor):
                        A_						:  Tuple          =				value.to("""cpu""")
                        if value.dtype == torch.inta:
                              A_						:  int          =				version.parse(importlib.metadata.version("""bitsandbytes""")) > version.parse(
                                  """0.37.2""")
                              if not is_abit_serializable:
                                    raise ValueError(
                                        """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
                                        """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""")
                  else:
                        A_						:  List[str]          =				torch.tensor(lowerCamelCase							,						device="""cpu""")

                  # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                  # Since weights are saved in the correct "orientation", we skip transposing when loading.
                  if issubclass(module.source_cls							,						lowerCamelCase) and fpaa_statistics is None:
                        A_						:  Tuple          =				new_value.T

                  A_						:  str          =				old_value.__dict__
                  if is_abit:
                        A_						:  Dict          =				bnb.nn.IntaParams(lowerCamelCase							,						requires_grad=lowerCamelCase							,						**lowerCamelCase).to(lowerCamelCase)
                  elif is_abit:
                        A_						:  List[str]          =				bnb.nn.Paramsabit(lowerCamelCase							,						requires_grad=lowerCamelCase							,						**lowerCamelCase).to(lowerCamelCase)

                  A_						:  Union[str, Any]          =				new_value
                  if fpaa_statistics is not None:
                        setattr(module.weight							,						"""SCB"""							,						fpaa_statistics.to(lowerCamelCase))

      else:
            if value is None:
                  A_						:  Optional[Any]          =				old_value.to(lowerCamelCase)
            elif isinstance(lowerCamelCase							,						torch.Tensor):
                  A_						:  List[Any]          =				value.to(lowerCamelCase)
            else:
                  A_						:  Any          =				torch.tensor(lowerCamelCase							,						device=lowerCamelCase)

            if is_buffer:
                  A_						:  Dict          =				new_value
            else:
                  A_						:  List[Any]          =				nn.Parameter(lowerCamelCase							,						requires_grad=old_value.requires_grad)
                  A_						:  Any          =				new_value




def      lowerCamelCase					(      lowerCamelCase  :      List[str]							,						lowerCamelCase  :      Optional[Any]=None							,						lowerCamelCase  :      int=None							,						lowerCamelCase  :      Optional[Any]=None							,						lowerCamelCase  :      List[Any]=False):
      for name, module in model.named_children():
            if current_key_name is None:
                  A_						:  Tuple          =				[]
            current_key_name.append(lowerCamelCase)

            if (isinstance(lowerCamelCase							,						nn.Linear) or isinstance(lowerCamelCase							,						lowerCamelCase)) and name not in modules_to_not_convert:
                  # Check if the current key is not in the `modules_to_not_convert`
                  if not any(key in """.""".join(lowerCamelCase) for key in modules_to_not_convert):
                        with init_empty_weights():
                              if isinstance(lowerCamelCase							,						lowerCamelCase):
                                    A_						:  List[Any]          =				module.weight.shape
                              else:
                                    A_						:  Optional[Any]          =				module.in_features
                                    A_						:  Dict          =				module.out_features

                              if quantization_config.quantization_method() == "llm_int8":
                                    A_						:  List[Any]          =				bnb.nn.LinearabitLt(
                                        lowerCamelCase							,						lowerCamelCase							,						module.bias is not None							,						has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight							,						threshold=quantization_config.llm_inta_threshold							,						)
                                    A_						:  Any          =				True
                              else:
                                    if (
                                        quantization_config.llm_inta_skip_modules is not None
                                        and name in quantization_config.llm_inta_skip_modules
                                    ):
                                          pass
                                    else:
                                          A_						:  Optional[int]          =				bnb.nn.Linearabit(
                                              lowerCamelCase							,						lowerCamelCase							,						module.bias is not None							,						quantization_config.bnb_abit_compute_dtype							,						compress_statistics=quantization_config.bnb_abit_use_double_quant							,						quant_type=quantization_config.bnb_abit_quant_type							,						)
                                          A_						:  Tuple          =				True
                    # Store the module class in case we need to transpose the weight later
                              A_						:  int          =				type(lowerCamelCase)
                              # Force requires grad to False to avoid unexpected errors
                              model._modules[name].requires_grad_(lowerCamelCase)
            if len(list(module.children())) > 0:
                  A_						:  Any          =				_replace_with_bnb_linear(
                      lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase							,						has_been_replaced=lowerCamelCase							,						)
            # Remove the last key for recursion
            current_key_name.pop(-1)
      return model, has_been_replaced




def      lowerCamelCase					(      lowerCamelCase  :      List[str]							,						lowerCamelCase  :      Optional[Any]=None							,						lowerCamelCase  :      str=None							,						lowerCamelCase  :      Union[str, Any]=None):
      A_						:  str          =				["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
      A_						:  str          =				_replace_with_bnb_linear(
          lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase							,						lowerCamelCase)

      if not has_been_replaced:
            logger.warning(
                """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
                """ Please double check your model architecture, or submit an issue on github if you think this is"""
                """ a bug.""")

      return model




def      lowerCamelCase					(      *lowerCamelCase  :      List[Any]							,						**lowerCamelCase  :      Union[str, Any]):
      warnings.warn(
          """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""							,						lowerCamelCase							,						)
      return replace_with_bnb_linear(*lowerCamelCase							,						**lowerCamelCase)




def      lowerCamelCase					(      *lowerCamelCase  :      Tuple							,						**lowerCamelCase  :      Dict):
      warnings.warn(
          """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""							,						lowerCamelCase							,						)
      return set_module_quantized_tensor_to_device(*lowerCamelCase							,						**lowerCamelCase)






def      lowerCamelCase					(      lowerCamelCase  :      Tuple):
      A_						:  str          =				deepcopy(lowerCamelCase)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
      tied_model.tie_weights()

      A_						:  Optional[Any]          =				find_tied_parameters(lowerCamelCase)
      # For compatibility with Accelerate < 0.18
      if isinstance(lowerCamelCase							,						lowerCamelCase):
            A_						:  str          =				sum(list(tied_params.values())							,						[]) + list(tied_params.keys())
      else:
            A_						:  Dict          =				sum(lowerCamelCase							,						[])
      A_						:  List[Any]          =				len(lowerCamelCase) > 0

      # Check if it is a base model
      A_						:  Union[str, Any]          =				not hasattr(lowerCamelCase							,						model.base_model_prefix)

      # Ignore this for base models (BertModel, GPT2Model, etc.)
      if (not has_tied_params) and is_base_model:
            return []

      # otherwise they have an attached head
      A_						:  int          =				list(model.named_children())
      A_						:  List[Any]          =				[list_modules[-1][0]]

      # add last module together with tied weights
      A_						:  Any          =				set(lowerCamelCase) - set(lowerCamelCase)
      A_						:  Any          =				list(set(lowerCamelCase)) + list(lowerCamelCase)

      # remove ".weight" from the keys
      A_						:  Dict          =				[""".weight""", """.bias"""]
      A_						:  Union[str, Any]          =				[]
      for name in list_untouched:
            for name_to_remove in names_to_remove:
                  if name_to_remove in name:
                        A_						:  Any          =				name.replace(lowerCamelCase							,						"""""")
            filtered_module_names.append(lowerCamelCase)

      return filtered_module_names




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


__magic_name__			=      logging.get_logger(__name__)

__magic_name__			=      {
    '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		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							"""owlvit_text_model"""






  def __init__(							self :       Union[str, Any]	,_a :       Any=49408	,_a :       Any=512	,_a :       Tuple=2048	,_a :       Dict=12	,_a :       Optional[int]=8	,_a :       Tuple=16	,_a :       Tuple="quick_gelu"	,_a :       Optional[Any]=1e-5	,_a :       List[Any]=0.0	,_a :       Optional[int]=0.02	,_a :       Dict=1.0	,_a :       Dict=0	,_a :       Any=49406	,_a :       Tuple=49407	,**_a :       List[Any]	,):

        '''simple docstring'''




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

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






  @classmethod
  def        _a							(							cls :       List[str]	,_a :       Union[str, os.PathLike]	,**_a :       str ):

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  int          =				cls.get_config_dict(_a	,**_a )

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


  '''simple docstring'''







  a_  					=							"""owlvit_vision_model"""






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

        '''simple docstring'''




        super().__init__(**_a )

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






  @classmethod
  def        _a							(							cls :       List[Any]	,_a :       Union[str, os.PathLike]	,**_a :       str ):

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  Optional[int]          =				cls.get_config_dict(_a	,**_a )

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


  '''simple docstring'''







  a_  					=							"""owlvit"""
  a_  					=							True






  def __init__(							self :       Union[str, Any]	,_a :       List[str]=None	,_a :       List[str]=None	,_a :       Dict=512	,_a :       List[Any]=2.6592	,_a :       Optional[Any]=True	,**_a :       Optional[int]	,):

        '''simple docstring'''




        super().__init__(**_a )

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

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

        A_						:  Dict          =				OwlViTTextConfig(**_a )
        A_						:  Dict          =				OwlViTVisionConfig(**_a )

        A_						:  Any          =				projection_dim
        A_						:  Optional[int]          =				logit_scale_init_value
        A_						:  Optional[int]          =				return_dict
        A_						:  Dict          =				1.0






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

        '''simple docstring'''




        cls._set_token_in_kwargs(_a )

        A_   ,					A_						:  List[Any]          =				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        _a							(							cls :       int	,_a :       Dict	,_a :       Dict	,**_a :       List[str] ):

        '''simple docstring'''




        A_						:  str          =				{}
        A_						:  int          =				text_config
        A_						:  Union[str, Any]          =				vision_config

        return cls.from_dict(_a	,**_a )






  def        _a							(							self :       Optional[int] ):

        '''simple docstring'''




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







class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  @property
  def        _a							(							self :       int ):

        '''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        _a							(							self :       str ):

        '''simple docstring'''




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






  @property
  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        return 1e-4






  def        _a							(							self :       int	,_a :       "ProcessorMixin"	,_a :       int = -1	,_a :       int = -1	,_a :       Optional["TensorType"] = None	,):

        '''simple docstring'''




        A_						:  Any          =				super().generate_dummy_inputs(
            processor.tokenizer	,batch_size=_a	,seq_length=_a	,framework=_a )
        A_						:  Any          =				super().generate_dummy_inputs(
            processor.image_processor	,batch_size=_a	,framework=_a )
        return {**text_input_dict, **image_input_dict}






  @property
  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        return 14
