


import inspect
from typing import Optional, Union

import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
    PIL_INTERPOLATION,
    randn_tensor,
)


def 		lowercase_  (     _UpperCamelCase       ,			_UpperCamelCase       ,			_UpperCamelCase  ):


			'''simple docstring'''







			if isinstance(a_       ,			torch.Tensor  ):
						return image
			elif isinstance(a_       ,			PIL.Image.Image  ):
						__lowercase 					=   [image]

			if isinstance(image[0]       ,			PIL.Image.Image  ):
						__lowercase 					=   [np.array(i.resize((w, h)       ,			resample=PIL_INTERPOLATION['''lanczos''']  )  )[None, :] for i in image]
						__lowercase 					=   np.concatenate(a_       ,			axis=0  )
						__lowercase 					=   np.array(a_  ).astype(np.floataa  ) / 255.0
						__lowercase 					=   image.transpose(0       ,			3       ,			1       ,			2  )
						__lowercase 					=   2.0 * image - 1.0
						__lowercase 					=   torch.from_numpy(a_  )
			elif isinstance(image[0]       ,			torch.Tensor  ):
						__lowercase 					=   torch.cat(a_       ,			dim=0  )
			return image


def 		lowercase_  (     _UpperCamelCase       ,			_UpperCamelCase       ,			_UpperCamelCase       ,			_UpperCamelCase=0.9995  ):


			'''simple docstring'''







			if not isinstance(a_       ,			np.ndarray  ):
						__lowercase 					=   True
						__lowercase 					=   va.device
						__lowercase 					=   va.cpu().numpy()
						__lowercase 					=   va.cpu().numpy()

			__lowercase 					=   np.sum(va * va / (np.linalg.norm(a_  ) * np.linalg.norm(a_  ))  )
			if np.abs(a_  ) > DOT_THRESHOLD:
						__lowercase 					=   (1 - t) * va + t * va
			else:
						__lowercase 					=   np.arccos(a_  )
						__lowercase 					=   np.sin(a_  )
						__lowercase 					=   theta_a * t
						__lowercase 					=   np.sin(a_  )
						__lowercase 					=   np.sin(theta_a - theta_t  ) / sin_theta_a
						__lowercase 					=   sin_theta_t / sin_theta_a
						__lowercase 					=   sa * va + sa * va

			if inputs_are_torch:
						__lowercase 					=   torch.from_numpy(a_  ).to(a_  )

			return va


def 		lowercase_  (     _UpperCamelCase       ,			_UpperCamelCase  ):


			'''simple docstring'''







			__lowercase 					=   F.normalize(a_       ,			dim=-1  )
			__lowercase 					=   F.normalize(a_       ,			dim=-1  )
			return (x - y).norm(dim=-1  ).div(2  ).arcsin().pow(2  ).mul(2  )


def 		lowercase_  (     _UpperCamelCase       ,			_UpperCamelCase  ):


			'''simple docstring'''







			for param in model.parameters():
						__lowercase 					=   value





class 	lowerCamelCase_       (				__SCREAMING_SNAKE_CASE				):



					'''simple docstring'''







					def __init__(				self ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_=None ,       snake_case_=None ,       snake_case_=None ,       )   ->			Tuple:







								'''simple docstring'''

								super().__init__()
								self.register_modules(
								    vae=__snake_case ,       text_encoder=__snake_case ,       clip_model=__snake_case ,       tokenizer=__snake_case ,       unet=__snake_case ,       scheduler=__snake_case ,       feature_extractor=__snake_case ,       coca_model=__snake_case ,       coca_tokenizer=__snake_case ,       coca_transform=__snake_case ,       )
								__lowercase 					=   (
								    feature_extractor.size
								    if isinstance(feature_extractor.size ,       __snake_case						)
								    else feature_extractor.size['''shortest_edge''']
								)
								__lowercase 					=   transforms.Normalize(mean=feature_extractor.image_mean ,       std=feature_extractor.image_std						)
								set_requires_grad(self.text_encoder ,       __snake_case						)
								set_requires_grad(self.clip_model ,       __snake_case						)






					def A      (				self ,       snake_case_ = "auto"						)   ->			Optional[int]:







								'''simple docstring'''

								if slice_size == "auto":
											# half the attention head size is usually a good trade-off between
											# speed and memory
											__lowercase 					=   self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(__snake_case						)






					def A      (				self						)   ->			Any:







								'''simple docstring'''

								self.enable_attention_slicing(__snake_case						)






					def A      (				self						)   ->			List[Any]:







								'''simple docstring'''

								set_requires_grad(self.vae ,       __snake_case						)






					def A      (				self						)   ->			Optional[Any]:







								'''simple docstring'''

								set_requires_grad(self.vae ,       __snake_case						)






					def A      (				self						)   ->			str:







								'''simple docstring'''

								set_requires_grad(self.unet ,       __snake_case						)






					def A      (				self						)   ->			int:







								'''simple docstring'''

								set_requires_grad(self.unet ,       __snake_case						)






					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_						)   ->			str:







								'''simple docstring'''

								__lowercase 					=   min(int(num_inference_steps * strength						) ,       __snake_case						)

								__lowercase 					=   max(num_inference_steps - init_timestep ,       0						)
								__lowercase 					=   self.scheduler.timesteps[t_start:]

								return timesteps, num_inference_steps - t_start






					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_=None						)   ->			List[str]:







								'''simple docstring'''

								if not isinstance(__snake_case ,       torch.Tensor						):
											raise ValueError(F'`image` has to be of type `torch.Tensor` but is {type(__snake_case						)}'						)

								__lowercase 					=   image.to(device=__snake_case ,       dtype=__snake_case						)

								if isinstance(__snake_case ,       __snake_case						):
											__lowercase 					=   [
											    self.vae.encode(image[i : i + 1]						).latent_dist.sample(generator[i]						) for i in range(__snake_case						)
											]
											__lowercase 					=   torch.cat(__snake_case ,       dim=0						)
								else:
											__lowercase 					=   self.vae.encode(__snake_case						).latent_dist.sample(__snake_case						)

								# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
								__lowercase 					=   0.1_8_2_1_5 * init_latents
								__lowercase 					=   init_latents.repeat_interleave(__snake_case ,       dim=0						)

								__lowercase 					=   randn_tensor(init_latents.shape ,       generator=__snake_case ,       device=__snake_case ,       dtype=__snake_case						)

								# get latents
								__lowercase 					=   self.scheduler.add_noise(__snake_case ,       __snake_case ,       __snake_case						)
								__lowercase 					=   init_latents

								return latents






					def A      (				self ,       snake_case_						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   self.coca_transform(__snake_case						).unsqueeze(0						)
								with torch.no_grad(), torch.cuda.amp.autocast():
											__lowercase 					=   self.coca_model.generate(transformed_image.to(device=self.device ,       dtype=self.coca_model.dtype						)						)
								__lowercase 					=   self.coca_tokenizer.decode(generated[0].cpu().numpy()						)
								return generated.split('''<end_of_text>'''						)[0].replace('''<start_of_text>''' ,       ''''''						).rstrip(''' .,'''						)






					def A      (				self ,       snake_case_ ,       snake_case_						)   ->			Optional[Any]:







								'''simple docstring'''

								__lowercase 					=   self.feature_extractor.preprocess(__snake_case						)
								__lowercase 					=   torch.from_numpy(clip_image_input['''pixel_values'''][0]						).unsqueeze(0						).to(self.device						).half()
								__lowercase 					=   self.clip_model.get_image_features(__snake_case						)
								__lowercase 					=   image_embeddings_clip / image_embeddings_clip.norm(p=2 ,       dim=-1 ,       keepdim=__snake_case						)
								__lowercase 					=   image_embeddings_clip.repeat_interleave(__snake_case ,       dim=0						)
								return image_embeddings_clip






					@torch.enable_grad()
					def A      (				self ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       snake_case_ ,       )   ->			int:







								'''simple docstring'''

								__lowercase 					=   latents.detach().requires_grad_()

								__lowercase 					=   self.scheduler.scale_model_input(__snake_case ,       __snake_case						)

								# predict the noise residual
								__lowercase 					=   self.unet(__snake_case ,       __snake_case ,       encoder_hidden_states=__snake_case						).sample

								if isinstance(self.scheduler ,       (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)						):
											__lowercase 					=   self.scheduler.alphas_cumprod[timestep]
											__lowercase 					=   1 - alpha_prod_t
											# compute predicted original sample from predicted noise also called
											# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
											__lowercase 					=   (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

											__lowercase 					=   torch.sqrt(__snake_case						)
											__lowercase 					=   pred_original_sample * (fac) + latents * (1 - fac)
								elif isinstance(self.scheduler ,       __snake_case						):
											__lowercase 					=   self.scheduler.sigmas[index]
											__lowercase 					=   latents - sigma * noise_pred
								else:
											raise ValueError(F'scheduler type {type(self.scheduler						)} not supported'						)

								# Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
								__lowercase 					=   1 / 0.1_8_2_1_5 * sample
								__lowercase 					=   self.vae.decode(__snake_case						).sample
								__lowercase 					=   (image / 2 + 0.5).clamp(0 ,       1						)

								__lowercase 					=   transforms.Resize(self.feature_extractor_size						)(__snake_case						)
								__lowercase 					=   self.normalize(__snake_case						).to(latents.dtype						)

								__lowercase 					=   self.clip_model.get_image_features(__snake_case						)
								__lowercase 					=   image_embeddings_clip / image_embeddings_clip.norm(p=2 ,       dim=-1 ,       keepdim=__snake_case						)

								__lowercase 					=   spherical_dist_loss(__snake_case ,       __snake_case						).mean() * clip_guidance_scale

								__lowercase 					=   -torch.autograd.grad(__snake_case ,       __snake_case						)[0]

								if isinstance(self.scheduler ,       __snake_case						):
											__lowercase 					=   latents.detach() + grads * (sigma**2)
											__lowercase 					=   noise_pred_original
								else:
											__lowercase 					=   noise_pred_original - torch.sqrt(__snake_case						) * grads
								return noise_pred, latents






					@torch.no_grad()
					def __call__(				self ,       snake_case_ ,       snake_case_ ,       snake_case_ = None ,       snake_case_ = None ,       snake_case_ = 5_1_2 ,       snake_case_ = 5_1_2 ,       snake_case_ = 0.6 ,       snake_case_ = 5_0 ,       snake_case_ = 7.5 ,       snake_case_ = 1 ,       snake_case_ = 0.0 ,       snake_case_ = 1_0_0 ,       snake_case_ = None ,       snake_case_ = "pil" ,       snake_case_ = True ,       snake_case_ = 0.8 ,       snake_case_ = 0.1 ,       snake_case_ = 0.1 ,       )   ->			Dict:







								'''simple docstring'''

								if isinstance(__snake_case ,       __snake_case						) and len(__snake_case						) != batch_size:
											raise ValueError(F'You have passed {batch_size} batch_size, but only {len(__snake_case						)} generators.'						)

								if height % 8 != 0 or width % 8 != 0:
											raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.'						)

								if isinstance(__snake_case ,       torch.Generator						) and batch_size > 1:
											__lowercase 					=   [generator] + [None] * (batch_size - 1)

								__lowercase 					=   [
								    ('''model''', self.coca_model is None),
								    ('''tokenizer''', self.coca_tokenizer is None),
								    ('''transform''', self.coca_transform is None),
								]
								__lowercase 					=   [x[0] for x in coca_is_none if x[1]]
								__lowercase 					=   ''', '''.join(__snake_case						)
								# generate prompts with coca model if prompt is None
								if content_prompt is None:
											if len(__snake_case						):
														raise ValueError(
														    F'Content prompt is None and CoCa [{coca_is_none_str}] is None.'
														    F'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.'						)
											__lowercase 					=   self.get_image_description(__snake_case						)
								if style_prompt is None:
											if len(__snake_case						):
														raise ValueError(
														    F'Style prompt is None and CoCa [{coca_is_none_str}] is None.'
														    F' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.'						)
											__lowercase 					=   self.get_image_description(__snake_case						)

								# get prompt text embeddings for content and style
								__lowercase 					=   self.tokenizer(
								    __snake_case ,       padding='''max_length''' ,       max_length=self.tokenizer.model_max_length ,       truncation=__snake_case ,       return_tensors='''pt''' ,       )
								__lowercase 					=   self.text_encoder(content_text_input.input_ids.to(self.device						)						)[0]

								__lowercase 					=   self.tokenizer(
								    __snake_case ,       padding='''max_length''' ,       max_length=self.tokenizer.model_max_length ,       truncation=__snake_case ,       return_tensors='''pt''' ,       )
								__lowercase 					=   self.text_encoder(style_text_input.input_ids.to(self.device						)						)[0]

								__lowercase 					=   slerp(__snake_case ,       __snake_case ,       __snake_case						)

								# duplicate text embeddings for each generation per prompt
								__lowercase 					=   text_embeddings.repeat_interleave(__snake_case ,       dim=0						)

								# set timesteps
								__lowercase 					=   '''offset''' in set(inspect.signature(self.scheduler.set_timesteps						).parameters.keys()						)
								__lowercase 					=   {}
								if accepts_offset:
											__lowercase 					=   1

								self.scheduler.set_timesteps(__snake_case ,       **__snake_case						)
								# Some schedulers like PNDM have timesteps as arrays
								# It's more optimized to move all timesteps to correct device beforehand
								self.scheduler.timesteps.to(self.device						)

								__lowercase 					=   self.get_timesteps(__snake_case ,       __snake_case ,       self.device						)
								__lowercase 					=   timesteps[:1].repeat(__snake_case						)

								# Preprocess image
								__lowercase 					=   preprocess(__snake_case ,       __snake_case ,       __snake_case						)
								__lowercase 					=   self.prepare_latents(
								    __snake_case ,       __snake_case ,       __snake_case ,       text_embeddings.dtype ,       self.device ,       __snake_case						)

								__lowercase 					=   preprocess(__snake_case ,       __snake_case ,       __snake_case						)
								__lowercase 					=   self.prepare_latents(
								    __snake_case ,       __snake_case ,       __snake_case ,       text_embeddings.dtype ,       self.device ,       __snake_case						)

								__lowercase 					=   slerp(__snake_case ,       __snake_case ,       __snake_case						)

								if clip_guidance_scale > 0:
											__lowercase 					=   self.get_clip_image_embeddings(__snake_case ,       __snake_case						)
											__lowercase 					=   self.get_clip_image_embeddings(__snake_case ,       __snake_case						)
											__lowercase 					=   slerp(
											    __snake_case ,       __snake_case ,       __snake_case						)

								# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
								# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
								# corresponds to doing no classifier free guidance.
								__lowercase 					=   guidance_scale > 1.0
								# get unconditional embeddings for classifier free guidance
								if do_classifier_free_guidance:
											__lowercase 					=   content_text_input.input_ids.shape[-1]
											__lowercase 					=   self.tokenizer([''''''] ,       padding='''max_length''' ,       max_length=__snake_case ,       return_tensors='''pt'''						)
											__lowercase 					=   self.text_encoder(uncond_input.input_ids.to(self.device						)						)[0]
											# duplicate unconditional embeddings for each generation per prompt
											__lowercase 					=   uncond_embeddings.repeat_interleave(__snake_case ,       dim=0						)

											# For classifier free guidance, we need to do two forward passes.
											# Here we concatenate the unconditional and text embeddings into a single batch
											# to avoid doing two forward passes
											__lowercase 					=   torch.cat([uncond_embeddings, text_embeddings]						)

								# get the initial random noise unless the user supplied it

								# Unlike in other pipelines, latents need to be generated in the target device
								# for 1-to-1 results reproducibility with the CompVis implementation.
								# However this currently doesn't work in `mps`.
								__lowercase 					=   (batch_size, self.unet.config.in_channels, height // 8, width // 8)
								__lowercase 					=   text_embeddings.dtype
								if latents is None:
											if self.device.type == "mps":
														# randn does not work reproducibly on mps
														__lowercase 					=   torch.randn(__snake_case ,       generator=__snake_case ,       device='''cpu''' ,       dtype=__snake_case						).to(
														    self.device						)
											else:
														__lowercase 					=   torch.randn(__snake_case ,       generator=__snake_case ,       device=self.device ,       dtype=__snake_case						)
								else:
											if latents.shape != latents_shape:
														raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}'						)
											__lowercase 					=   latents.to(self.device						)

								# scale the initial noise by the standard deviation required by the scheduler
								__lowercase 					=   latents * self.scheduler.init_noise_sigma

								# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
								# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
								# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
								# and should be between [0, 1]
								__lowercase 					=   '''eta''' in set(inspect.signature(self.scheduler.step						).parameters.keys()						)
								__lowercase 					=   {}
								if accepts_eta:
											__lowercase 					=   eta

								# check if the scheduler accepts generator
								__lowercase 					=   '''generator''' in set(inspect.signature(self.scheduler.step						).parameters.keys()						)
								if accepts_generator:
											__lowercase 					=   generator

								with self.progress_bar(total=__snake_case						):
											for i, t in enumerate(__snake_case						):
														# expand the latents if we are doing classifier free guidance
														__lowercase 					=   torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
														__lowercase 					=   self.scheduler.scale_model_input(__snake_case ,       __snake_case						)

														# predict the noise residual
														__lowercase 					=   self.unet(__snake_case ,       __snake_case ,       encoder_hidden_states=__snake_case						).sample

														# perform classifier free guidance
														if do_classifier_free_guidance:
																	__lowercase 					=   noise_pred.chunk(2						)
																	__lowercase 					=   noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

														# perform clip guidance
														if clip_guidance_scale > 0:
																	__lowercase 					=   (
																	    text_embeddings.chunk(2						)[1] if do_classifier_free_guidance else text_embeddings
																	)
																	__lowercase 					=   self.cond_fn(
																	    __snake_case ,       __snake_case ,       __snake_case ,       __snake_case ,       __snake_case ,       __snake_case ,       __snake_case ,       )

														# compute the previous noisy sample x_t -> x_t-1
														__lowercase 					=   self.scheduler.step(__snake_case ,       __snake_case ,       __snake_case ,       **__snake_case						).prev_sample

        # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
								__lowercase 					=   1 / 0.1_8_2_1_5 * latents
								__lowercase 					=   self.vae.decode(__snake_case						).sample

								__lowercase 					=   (image / 2 + 0.5).clamp(0 ,       1						)
								__lowercase 					=   image.cpu().permute(0 ,       2 ,       3 ,       1						).numpy()

								if output_type == "pil":
											__lowercase 					=   self.numpy_to_pil(__snake_case						)

								if not return_dict:
											return (image, None)

								return StableDiffusionPipelineOutput(images=__snake_case ,       nsfw_content_detected=__snake_case						)



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 : Union[str, Any]		=				logging.get_logger(__name__)

a : Any		=				{
    '''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_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit_text_model"






					def __init__(				self ,       snake_case_=4_9_4_0_8 ,       snake_case_=5_1_2 ,       snake_case_=2_0_4_8 ,       snake_case_=1_2 ,       snake_case_=8 ,       snake_case_=1_6 ,       snake_case_="quick_gelu" ,       snake_case_=1e-5 ,       snake_case_=0.0 ,       snake_case_=0.0_2 ,       snake_case_=1.0 ,       snake_case_=0 ,       snake_case_=4_9_4_0_6 ,       snake_case_=4_9_4_0_7 ,       **snake_case_ ,       )   ->			int:







								'''simple docstring'''

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

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






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

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




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit_vision_model"






					def __init__(				self ,       snake_case_=7_6_8 ,       snake_case_=3_0_7_2 ,       snake_case_=1_2 ,       snake_case_=1_2 ,       snake_case_=3 ,       snake_case_=7_6_8 ,       snake_case_=3_2 ,       snake_case_="quick_gelu" ,       snake_case_=1e-5 ,       snake_case_=0.0 ,       snake_case_=0.0_2 ,       snake_case_=1.0 ,       **snake_case_ ,       )   ->			Any:







								'''simple docstring'''

								super().__init__(**snake_case_						)

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






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

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




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					__UpperCAmelCase            =				"owlvit"
					__UpperCAmelCase            =				True






					def __init__(				self ,       snake_case_=None ,       snake_case_=None ,       snake_case_=5_1_2 ,       snake_case_=2.6_5_9_2 ,       snake_case_=True ,       **snake_case_ ,       )   ->			Optional[Any]:







								'''simple docstring'''

								super().__init__(**snake_case_						)

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

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

								__lowercase 					=   OwlViTTextConfig(**snake_case_						)
								__lowercase 					=   OwlViTVisionConfig(**snake_case_						)

								__lowercase 					=   projection_dim
								__lowercase 					=   logit_scale_init_value
								__lowercase 					=   return_dict
								__lowercase 					=   1.0






					@classmethod
					def A      (				cls ,       snake_case_ ,       **snake_case_						)   ->			"PretrainedConfig":







								'''simple docstring'''

								cls._set_token_in_kwargs(snake_case_						)

								__lowercase					, __lowercase 					=   cls.get_config_dict(snake_case_ ,       **snake_case_						)

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






					@classmethod
					def A      (				cls ,       snake_case_ ,       snake_case_ ,       **snake_case_						)   ->			int:







								'''simple docstring'''

								__lowercase 					=   {}
								__lowercase 					=   text_config
								__lowercase 					=   vision_config

								return cls.from_dict(snake_case_ ,       **snake_case_						)






					def A      (				self						)   ->			Any:







								'''simple docstring'''

								__lowercase 					=   copy.deepcopy(self.__dict__						)
								__lowercase 					=   self.text_config.to_dict()
								__lowercase 					=   self.vision_config.to_dict()
								__lowercase 					=   self.__class__.model_type
								return output




class 	lowerCamelCase_       (				lowerCAmelCase__				):



					'''simple docstring'''







					@property
					def A      (				self						)   ->			Mapping[str, Mapping[int, str]]:







								'''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						)   ->			Mapping[str, Mapping[int, 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						)   ->			float:







								'''simple docstring'''

								return 1e-4






					def A      (				self ,       snake_case_ ,       snake_case_ = -1 ,       snake_case_ = -1 ,       snake_case_ = None ,       )   ->			Mapping[str, Any]:







								'''simple docstring'''

								__lowercase 					=   super().generate_dummy_inputs(
								    processor.tokenizer ,       batch_size=snake_case_ ,       seq_length=snake_case_ ,       framework=snake_case_						)
								__lowercase 					=   super().generate_dummy_inputs(
								    processor.image_processor ,       batch_size=snake_case_ ,       framework=snake_case_						)
								return {**text_input_dict, **image_input_dict}






					@property
					def A      (				self						)   ->			int:







								'''simple docstring'''

								return 1_4


