






import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput

def      lowerCAmelCase__	(    _a       :			Dict  ,      _a       :			Optional[Any]=0.999  ,      _a       :			Dict="cosine"  ,      ):
		if alpha_transform_type == "cosine":

				def alpha_bar_fn(_a       :			Optional[Any]    ):
						return math.cos((t + 0.008) / 1.008 * math.pi / 2    ) ** 2

		elif alpha_transform_type == "exp":

				def alpha_bar_fn(_a       :			Optional[Any]    ):
						return math.exp(t * -12.0    )

		else:
				raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}'''    )

		snake_case_				:							Dict						 =       []
		for i in range(_a    ):
				snake_case_				:							List[str]						 =       i / num_diffusion_timesteps
				snake_case_				:							Dict						 =       (i + 1) / num_diffusion_timesteps
				betas.append(min(1 - alpha_bar_fn(_a    ) / alpha_bar_fn(_a    )  ,      _a    )    )
		return torch.tensor(_a  ,      dtype=torch.floataa    )




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					,  SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   Union[str, Any]						=					[e.name for e in KarrasDiffusionSchedulers]
						A     :   List[Any]						=					2






						@register_to_config
						def __init__(	self		,				_SCREAMING_SNAKE_CASE = 1000		,				_SCREAMING_SNAKE_CASE = 0.0_0085		,				_SCREAMING_SNAKE_CASE = 0.012		,				_SCREAMING_SNAKE_CASE = "linear"		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = "epsilon"		,				_SCREAMING_SNAKE_CASE = "linspace"		,				_SCREAMING_SNAKE_CASE = 0		,				) ->				Optional[Any]:
								if trained_betas is not None:
										snake_case_				:							Optional[Any]						 =       torch.tensor(_SCREAMING_SNAKE_CASE		,				dtype=torch.floataa				)
								elif beta_schedule == "linear":
										snake_case_				:							str						 =       torch.linspace(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				dtype=torch.floataa				)
								elif beta_schedule == "scaled_linear":
										# this schedule is very specific to the latent diffusion model.
										snake_case_				:							Optional[int]						 =       (
										    torch.linspace(beta_start**0.5		,				beta_end**0.5		,				_SCREAMING_SNAKE_CASE		,				dtype=torch.floataa				) ** 2
										)
								elif beta_schedule == "squaredcos_cap_v2":
										# Glide cosine schedule
										snake_case_				:							Any						 =       betas_for_alpha_bar(_SCREAMING_SNAKE_CASE				)
								else:
										raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}'''				)

								snake_case_				:							Any						 =       1.0 - self.betas
								snake_case_				:							Dict						 =       torch.cumprod(self.alphas		,				dim=0				)

								#  set all values
								self.set_timesteps(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=None				) ->				List[Any]:
								if schedule_timesteps is None:
										snake_case_				:							Tuple						 =       self.timesteps

								snake_case_				:							Optional[int]						 =       (schedule_timesteps == timestep).nonzero()

								# The sigma index that is taken for the **very** first `step`
								# is always the second index (or the last index if there is only 1)
								# This way we can ensure we don't accidentally skip a sigma in
								# case we start in the middle of the denoising schedule (e.g. for image-to-image)
								if len(self._index_counter				) == 0:
										snake_case_				:							List[Any]						 =       1 if len(_SCREAMING_SNAKE_CASE				) > 1 else 0
								else:
										snake_case_				:							Tuple						 =       timestep.cpu().item() if torch.is_tensor(_SCREAMING_SNAKE_CASE				) else timestep
										snake_case_				:							Optional[Any]						 =       self._index_counter[timestep_int]

								return indices[pos].item()






						@property
						def       _lowerCAmelCase       (	self				) ->				List[Any]:
								# standard deviation of the initial noise distribution
								if self.config.timestep_spacing in ["linspace", "trailing"]:
										return self.sigmas.max()

								return (self.sigmas.max() ** 2 + 1) ** 0.5






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				) ->				torch.FloatTensor:
								snake_case_				:							Optional[Any]						 =       self.index_for_timestep(_SCREAMING_SNAKE_CASE				)

								if self.state_in_first_order:
										snake_case_				:							Optional[Any]						 =       self.sigmas[step_index]
								else:
										snake_case_				:							Union[str, Any]						 =       self.sigmas_interpol[step_index]

								snake_case_				:							Dict						 =       sample / ((sigma**2 + 1) ** 0.5)
								return sample






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				) ->				Union[str, Any]:
								snake_case_				:							Dict						 =       num_inference_steps

								snake_case_				:							str						 =       num_train_timesteps or self.config.num_train_timesteps

								# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
								if self.config.timestep_spacing == "linspace":
										snake_case_				:							Optional[int]						 =       np.linspace(0		,				num_train_timesteps - 1		,				_SCREAMING_SNAKE_CASE		,				dtype=_SCREAMING_SNAKE_CASE				)[::-1].copy()
								elif self.config.timestep_spacing == "leading":
										snake_case_				:							int						 =       num_train_timesteps // self.num_inference_steps
										# creates integer timesteps by multiplying by ratio
										# casting to int to avoid issues when num_inference_step is power of 3
										snake_case_				:							Dict						 =       (np.arange(0		,				_SCREAMING_SNAKE_CASE				) * step_ratio).round()[::-1].copy().astype(_SCREAMING_SNAKE_CASE				)
										timesteps += self.config.steps_offset
								elif self.config.timestep_spacing == "trailing":
										snake_case_				:							Union[str, Any]						 =       num_train_timesteps / self.num_inference_steps
										# creates integer timesteps by multiplying by ratio
										# casting to int to avoid issues when num_inference_step is power of 3
										snake_case_				:							Any						 =       (np.arange(_SCREAMING_SNAKE_CASE		,				0		,				-step_ratio				)).round().copy().astype(_SCREAMING_SNAKE_CASE				)
										timesteps -= 1
								else:
										raise ValueError(
										    f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''				)

								snake_case_				:							Optional[int]						 =       np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5				)
								snake_case_				:							str						 =       torch.from_numpy(np.log(_SCREAMING_SNAKE_CASE				)				).to(_SCREAMING_SNAKE_CASE				)

								snake_case_				:							List[str]						 =       np.interp(_SCREAMING_SNAKE_CASE		,				np.arange(0		,				len(_SCREAMING_SNAKE_CASE				)				)		,				_SCREAMING_SNAKE_CASE				)
								snake_case_				:							int						 =       np.concatenate([sigmas, [0.0]]				).astype(np.floataa				)
								snake_case_				:							Union[str, Any]						 =       torch.from_numpy(_SCREAMING_SNAKE_CASE				).to(device=_SCREAMING_SNAKE_CASE				)

								# interpolate sigmas
								snake_case_				:							List[Any]						 =       sigmas.log().lerp(sigmas.roll(1				).log()		,				0.5				).exp()

								snake_case_				:							List[str]						 =       torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2				), sigmas[-1:]]				)
								snake_case_				:							Optional[Any]						 =       torch.cat(
								    [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2				), sigmas_interpol[-1:]]				)

								if str(_SCREAMING_SNAKE_CASE				).startswith("mps"				):
										# mps does not support float64
										snake_case_				:							Union[str, Any]						 =       torch.from_numpy(_SCREAMING_SNAKE_CASE				).to(_SCREAMING_SNAKE_CASE		,				dtype=torch.floataa				)
								else:
										snake_case_				:							str						 =       torch.from_numpy(_SCREAMING_SNAKE_CASE				).to(_SCREAMING_SNAKE_CASE				)

								# interpolate timesteps
								snake_case_				:							Dict						 =       self.sigma_to_t(_SCREAMING_SNAKE_CASE				).to(_SCREAMING_SNAKE_CASE		,				dtype=timesteps.dtype				)
								snake_case_				:							Tuple						 =       torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None])		,				dim=-1				).flatten()

								snake_case_				:							Union[str, Any]						 =       torch.cat([timesteps[:1], interleaved_timesteps]				)

								snake_case_				:							int						 =       None

								# for exp beta schedules, such as the one for `pipeline_shap_e.py`
								# we need an index counter
								snake_case_				:							List[str]						 =       defaultdict(_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
								# get log sigma
								snake_case_				:							Union[str, Any]						 =       sigma.log()

								# get distribution
								snake_case_				:							Optional[int]						 =       log_sigma - self.log_sigmas[:, None]

								# get sigmas range
								snake_case_				:							List[Any]						 =       dists.ge(0				).cumsum(dim=0				).argmax(dim=0				).clamp(max=self.log_sigmas.shape[0] - 2				)
								snake_case_				:							Optional[Any]						 =       low_idx + 1

								snake_case_				:							Union[str, Any]						 =       self.log_sigmas[low_idx]
								snake_case_				:							Union[str, Any]						 =       self.log_sigmas[high_idx]

								# interpolate sigmas
								snake_case_				:							Union[str, Any]						 =       (low - log_sigma) / (low - high)
								snake_case_				:							List[Any]						 =       w.clamp(0		,				1				)

								# transform interpolation to time range
								snake_case_				:							Union[str, Any]						 =       (1 - w) * low_idx + w * high_idx
								snake_case_				:							Optional[int]						 =       t.view(sigma.shape				)
								return t






						@property
						def       _lowerCAmelCase       (	self				) ->				Any:
								return self.sample is None






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = True		,				) ->				Union[SchedulerOutput, Tuple]:
								snake_case_				:							int						 =       self.index_for_timestep(_SCREAMING_SNAKE_CASE				)

								# advance index counter by 1
								snake_case_				:							Tuple						 =       timestep.cpu().item() if torch.is_tensor(_SCREAMING_SNAKE_CASE				) else timestep
								self._index_counter[timestep_int] += 1

								if self.state_in_first_order:
										snake_case_				:							List[str]						 =       self.sigmas[step_index]
										snake_case_				:							Optional[Any]						 =       self.sigmas_interpol[step_index + 1]
										snake_case_				:							Dict						 =       self.sigmas[step_index + 1]
								else:
										# 2nd order / KDPM2's method
										snake_case_				:							Any						 =       self.sigmas[step_index - 1]
										snake_case_				:							List[str]						 =       self.sigmas_interpol[step_index]
										snake_case_				:							Dict						 =       self.sigmas[step_index]

								# currently only gamma=0 is supported. This usually works best anyways.
								# We can support gamma in the future but then need to scale the timestep before
								# passing it to the model which requires a change in API
								snake_case_				:							List[Any]						 =       0
								snake_case_				:							List[Any]						 =       sigma * (gamma + 1)  # Note: sigma_hat == sigma for now

								# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
								if self.config.prediction_type == "epsilon":
										snake_case_				:							Union[str, Any]						 =       sigma_hat if self.state_in_first_order else sigma_interpol
										snake_case_				:							List[str]						 =       sample - sigma_input * model_output
								elif self.config.prediction_type == "v_prediction":
										snake_case_				:							Union[str, Any]						 =       sigma_hat if self.state_in_first_order else sigma_interpol
										snake_case_				:							List[str]						 =       model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
										    sample / (sigma_input**2 + 1)
										)
								elif self.config.prediction_type == "sample":
										raise NotImplementedError("prediction_type not implemented yet: sample"				)
								else:
										raise ValueError(
										    f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''				)

								if self.state_in_first_order:
										# 2. Convert to an ODE derivative for 1st order
										snake_case_				:							int						 =       (sample - pred_original_sample) / sigma_hat
										# 3. delta timestep
										snake_case_				:							int						 =       sigma_interpol - sigma_hat

										# store for 2nd order step
										snake_case_				:							List[str]						 =       sample
								else:
										# DPM-Solver-2
										# 2. Convert to an ODE derivative for 2nd order
										snake_case_				:							Tuple						 =       (sample - pred_original_sample) / sigma_interpol

										# 3. delta timestep
										snake_case_				:							Any						 =       sigma_next - sigma_hat

										snake_case_				:							List[Any]						 =       self.sample
										snake_case_				:							Optional[int]						 =       None

								snake_case_				:							Any						 =       sample + derivative * dt

								if not return_dict:
										return (prev_sample,)

								return SchedulerOutput(prev_sample=_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				) ->				torch.FloatTensor:
								# Make sure sigmas and timesteps have the same device and dtype as original_samples
								snake_case_				:							Optional[Any]						 =       self.sigmas.to(device=original_samples.device		,				dtype=original_samples.dtype				)
								if original_samples.device.type == "mps" and torch.is_floating_point(_SCREAMING_SNAKE_CASE				):
										# mps does not support float64
										snake_case_				:							List[str]						 =       self.timesteps.to(original_samples.device		,				dtype=torch.floataa				)
										snake_case_				:							Any						 =       timesteps.to(original_samples.device		,				dtype=torch.floataa				)
								else:
										snake_case_				:							Optional[int]						 =       self.timesteps.to(original_samples.device				)
										snake_case_				:							Union[str, Any]						 =       timesteps.to(original_samples.device				)

								snake_case_				:							Optional[Any]						 =       [self.index_for_timestep(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) for t in timesteps]

								snake_case_				:							Union[str, Any]						 =       sigmas[step_indices].flatten()
								while len(sigma.shape				) < len(original_samples.shape				):
										snake_case_				:							Any						 =       sigma.unsqueeze(-1				)

								snake_case_				:							Any						 =       original_samples + noise * sigma
								return noisy_samples






						def __len__(	self				) ->				str:
								return self.config.num_train_timesteps








import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase  :							int			  =    logging.get_logger(__name__)

lowercase  :							Any			  =    {
    '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   int						=					'altclip_text_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=25_0002		,				_SCREAMING_SNAKE_CASE=1024		,				_SCREAMING_SNAKE_CASE=24		,				_SCREAMING_SNAKE_CASE=16		,				_SCREAMING_SNAKE_CASE=4096		,				_SCREAMING_SNAKE_CASE="gelu"		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=514		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1e-05		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0		,				_SCREAMING_SNAKE_CASE=2		,				_SCREAMING_SNAKE_CASE="absolute"		,				_SCREAMING_SNAKE_CASE=True		,				_SCREAMING_SNAKE_CASE=768		,				**_SCREAMING_SNAKE_CASE		,				) ->				List[str]:
								super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE		,				bos_token_id=_SCREAMING_SNAKE_CASE		,				eos_token_id=_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[Any]						 =       vocab_size
								snake_case_				:							List[str]						 =       hidden_size
								snake_case_				:							Dict						 =       num_hidden_layers
								snake_case_				:							List[str]						 =       num_attention_heads
								snake_case_				:							Optional[int]						 =       hidden_act
								snake_case_				:							Optional[Any]						 =       intermediate_size
								snake_case_				:							List[str]						 =       hidden_dropout_prob
								snake_case_				:							Union[str, Any]						 =       attention_probs_dropout_prob
								snake_case_				:							Optional[Any]						 =       max_position_embeddings
								snake_case_				:							Any						 =       type_vocab_size
								snake_case_				:							int						 =       initializer_range
								snake_case_				:							str						 =       initializer_factor
								snake_case_				:							List[str]						 =       layer_norm_eps
								snake_case_				:							Any						 =       position_embedding_type
								snake_case_				:							Optional[int]						 =       use_cache
								snake_case_				:							int						 =       project_dim




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   List[Any]						=					'altclip_vision_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=3072		,				_SCREAMING_SNAKE_CASE=512		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=3		,				_SCREAMING_SNAKE_CASE=224		,				_SCREAMING_SNAKE_CASE=32		,				_SCREAMING_SNAKE_CASE="quick_gelu"		,				_SCREAMING_SNAKE_CASE=1e-5		,				_SCREAMING_SNAKE_CASE=0.0		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1.0		,				**_SCREAMING_SNAKE_CASE		,				) ->				Optional[Any]:
								super().__init__(**_SCREAMING_SNAKE_CASE				)

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






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				"PretrainedConfig":
								cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE				)

								snake_case_ ,       snake_case_				:							str						 =       cls.get_config_dict(_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

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




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   str						=					'altclip'
						A     :   Dict						=					True






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=2.6592		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								# If `_config_dict` exist, we use them for the backward compatibility.
								# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
								# of confusion!).
								snake_case_				:							Optional[Any]						 =       kwargs.pop("text_config_dict"		,				_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Dict						 =       kwargs.pop("vision_config_dict"		,				_SCREAMING_SNAKE_CASE				)

								super().__init__(**_SCREAMING_SNAKE_CASE				)

								# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
								# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
								# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
								if text_config_dict is not None:
										if text_config is None:
												snake_case_				:							Any						 =       {}

										# This is the complete result when using `text_config_dict`.
										snake_case_				:							str						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				).to_dict()

										# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
										for key, value in _text_config_dict.items():
												if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
														# If specified in `text_config_dict`
														if key in text_config_dict:
																snake_case_				:							Optional[Any]						 =       (
																    f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
																    f'''The value `text_config_dict["{key}"]` will be used instead.'''
																)
														# If inferred from default argument values (just to be super careful)
														else:
																snake_case_				:							Dict						 =       (
																    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																    f'''value `text_config["{key}"]` will be overriden.'''
																)
														logger.warning(_SCREAMING_SNAKE_CASE				)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
										text_config.update(_text_config_dict				)

								if vision_config_dict is not None:
										if vision_config is None:
												snake_case_				:							str						 =       {}

										# This is the complete result when using `vision_config_dict`.
										snake_case_				:							Optional[Any]						 =       AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE				).to_dict()
										# convert keys to string instead of integer
										if "id2label" in _vision_config_dict:
												snake_case_				:							Any						 =       {
												    str(_SCREAMING_SNAKE_CASE				): value for key, value in _vision_config_dict["id2label"].items()
												}

										# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
										for key, value in _vision_config_dict.items():
												if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
														# If specified in `vision_config_dict`
														if key in vision_config_dict:
																snake_case_				:							Dict						 =       (
																    f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
																    f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
																)
														# If inferred from default argument values (just to be super careful)
														else:
																snake_case_				:							Optional[Any]						 =       (
																    f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
																    f'''The value `vision_config["{key}"]` will be overriden.'''
																)
														logger.warning(_SCREAMING_SNAKE_CASE				)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
										vision_config.update(_vision_config_dict				)

								if text_config is None:
										snake_case_				:							Tuple						 =       {}
										logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."				)

								if vision_config is None:
										snake_case_				:							Optional[Any]						 =       {}
										logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."				)

								snake_case_				:							List[Any]						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Union[str, Any]						 =       AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[int]						 =       projection_dim
								snake_case_				:							Tuple						 =       logit_scale_init_value
								snake_case_				:							List[Any]						 =       1.0






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								return cls(text_config=text_config.to_dict()		,				vision_config=vision_config.to_dict()		,				**_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				List[str]:
								snake_case_				:							Any						 =       copy.deepcopy(self.__dict__				)
								snake_case_				:							Union[str, Any]						 =       self.text_config.to_dict()
								snake_case_				:							List[Any]						 =       self.vision_config.to_dict()
								snake_case_				:							Tuple						 =       self.__class__.model_type
								return output
