




'''simple docstring'''





import copy
import os
from typing import Union

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


_SCREAMING_SNAKE_CASE							:       Optional[int]						=			logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE							:       Optional[int]						=			{
    "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}




class 			_snake_case		(     lowercase_							):
   lowerCAmelCase_					:				List[Any]							=   "altclip_text_model"




   def __init__( self    ,							a__=250_002    ,							a__=1_024    ,							a__=24    ,							a__=16    ,							a__=4_096    ,							a__="gelu"    ,							a__=0.1    ,							a__=0.1    ,							a__=514    ,							a__=1    ,							a__=0.0_2    ,							a__=0.0_2    ,							a__=1e-05    ,							a__=1    ,							a__=0    ,							a__=2    ,							a__="absolute"    ,							a__=True    ,							a__=768    ,							**a__    ,							)    ->    Tuple:

          '''simple docstring'''




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

          snake_case_      =				vocab_size
          snake_case_      =				hidden_size
          snake_case_      =				num_hidden_layers
          snake_case_      =				num_attention_heads
          snake_case_      =				hidden_act
          snake_case_      =				intermediate_size
          snake_case_      =				hidden_dropout_prob
          snake_case_      =				attention_probs_dropout_prob
          snake_case_      =				max_position_embeddings
          snake_case_      =				type_vocab_size
          snake_case_      =				initializer_range
          snake_case_      =				initializer_factor
          snake_case_      =				layer_norm_eps
          snake_case_      =				position_embedding_type
          snake_case_      =				use_cache
          snake_case_      =				project_dim




class 			_snake_case		(     lowercase_							):
   lowerCAmelCase_					:				Tuple							=   "altclip_vision_model"




   def __init__( self    ,							a__=768    ,							a__=3_072    ,							a__=512    ,							a__=12    ,							a__=12    ,							a__=3    ,							a__=224    ,							a__=32    ,							a__="quick_gelu"    ,							a__=1e-5    ,							a__=0.0    ,							a__=0.0_2    ,							a__=1.0    ,							**a__    ,							)    ->    List[Any]:

          '''simple docstring'''




          super().__init__(**a__							)

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




   @classmethod
   def        lowerCAmelCase__    ( cls    ,							a__    ,							**a__							)    ->    "PretrainedConfig":

          '''simple docstring'''




          cls._set_token_in_kwargs(a__							)

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

          # get the vision config dict if we are loading from AltCLIPConfig
          if config_dict.get("model_type"							) == "altclip":
                 snake_case_      =				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 			_snake_case		(     lowercase_							):
   lowerCAmelCase_					:				Union[str, Any]							=   "altclip"
   lowerCAmelCase_					:				Tuple							=   True




   def __init__( self    ,							a__=None    ,							a__=None    ,							a__=768    ,							a__=2.6_5_9_2    ,							**a__							)    ->    Tuple:

          '''simple docstring'''




          snake_case_      =				kwargs.pop("text_config_dict"    ,							a__							)
          snake_case_      =				kwargs.pop("vision_config_dict"    ,							a__							)

          super().__init__(**a__							)

          # 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_      =				{}

                 # This is the complete result when using `text_config_dict`.
                 snake_case_      =				AltCLIPTextConfig(**a__							).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_      =				(
                                          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_      =				(
                                          F'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '
                                          F'value `text_config["{key}"]` will be overriden.'
                                      )
                               logger.warning(a__							)

            # 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_      =				{}

                 # This is the complete result when using `vision_config_dict`.
                 snake_case_      =				AltCLIPVisionConfig(**a__							).to_dict()
                 # convert keys to string instead of integer
                 if "id2label" in _vision_config_dict:
                        snake_case_      =				{
                            str(a__							): 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_      =				(
                                          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_      =				(
                                          F'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '
                                          F'The value `vision_config["{key}"]` will be overriden.'
                                      )
                               logger.warning(a__							)

            # 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_      =				{}
                 logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."							)

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

          snake_case_      =				AltCLIPTextConfig(**a__							)
          snake_case_      =				AltCLIPVisionConfig(**a__							)

          snake_case_      =				projection_dim
          snake_case_      =				logit_scale_init_value
          snake_case_      =				1.0




   @classmethod
   def        lowerCAmelCase__    ( cls    ,							a__    ,							a__    ,							**a__							)    ->    Optional[Any]:

          '''simple docstring'''




          return cls(text_config=text_config.to_dict()    ,							vision_config=vision_config.to_dict()    ,							**a__							)




   def        lowerCAmelCase__    ( self							)    ->    List[str]:

          '''simple docstring'''




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










'''simple docstring'''





import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


_SCREAMING_SNAKE_CASE							:       Any						=			False




class 			_snake_case		(     unittest.TestCase							):
			pass




@slow
@require_torch_gpu
class 			_snake_case		(     unittest.TestCase							):




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

										'''simple docstring'''




										snake_case_      =				VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion"							)
										pipe.to(a__							)
										pipe.set_progress_bar_config(disable=a__							)

										snake_case_      =				load_image(
										    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"							)
										snake_case_      =				torch.manual_seed(0							)
										snake_case_      =				pipe(
										    image=a__    ,							generator=a__    ,							guidance_scale=7.5    ,							num_inference_steps=50    ,							output_type="numpy"    ,							).images

										snake_case_      =				image[0, 253:256, 253:256, -1]

										assert image.shape == (1, 512, 512, 3)
										snake_case_      =				np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5]							)

										assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2




