'''simple docstring'''




import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class     __magic_name__						(    unittest.TestCase):







			def 	SCREAMING_SNAKE_CASE_     (	self				:  str    ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







			@property
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Dict    ):
										torch.manual_seed(0    )
										lowercase_					:			Any										=       UNetaDModel(
										    sample_size=(32, 64)				,			in_channels=1				,			out_channels=1				,			layers_per_block=2				,			block_out_channels=(128, 128)				,			down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")				,			up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")				,			)
										return model







			@property
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]    ):
										torch.manual_seed(0    )
										lowercase_					:			List[Any]										=       UNetaDConditionModel(
										    sample_size=(64, 32)				,			in_channels=1				,			out_channels=1				,			layers_per_block=2				,			block_out_channels=(128, 128)				,			down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")				,			up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")				,			cross_attention_dim=10				,			)
										return model







			@property
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Tuple    ):
										torch.manual_seed(0    )
										lowercase_					:			Optional[int]										=       AutoencoderKL(
										    sample_size=(128, 64)				,			in_channels=1				,			out_channels=1				,			latent_channels=1				,			layers_per_block=2				,			block_out_channels=(128, 128)				,			down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")				,			up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")				,			)
										lowercase_					:			Dict										=       UNetaDModel(
										    sample_size=(64, 32)				,			in_channels=1				,			out_channels=1				,			layers_per_block=2				,			block_out_channels=(128, 128)				,			down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")				,			up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")				,			)
										return vqvae, unet







			@slow
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			int										=       """cpu"""  # ensure determinism for the device-dependent torch.Generator
										lowercase_					:			List[Any]										=       Mel(
										    x_res=self.dummy_unet.config.sample_size[1]				,			y_res=self.dummy_unet.config.sample_size[0]				,			)

										lowercase_					:			Tuple										=       DDPMScheduler()
										lowercase_					:			Dict										=       AudioDiffusionPipeline(vqvae=lowercase_				,			unet=self.dummy_unet				,			mel=lowercase_				,			scheduler=lowercase_    )
										lowercase_					:			int										=       pipe.to(lowercase_    )
										pipe.set_progress_bar_config(disable=lowercase_    )

										lowercase_					:			str										=       torch.Generator(device=lowercase_    ).manual_seed(42    )
										lowercase_					:			Union[str, Any]										=       pipe(generator=lowercase_				,			steps=4    )
										lowercase_					:			Tuple										=       output.audios[0]
										lowercase_					:			Tuple										=       output.images[0]

										lowercase_					:			Any										=       torch.Generator(device=lowercase_    ).manual_seed(42    )
										lowercase_					:			int										=       pipe(generator=lowercase_				,			steps=4				,			return_dict=lowercase_    )
										lowercase_					:			Optional[int]										=       output[0][0]

										assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
										assert (
										    image.height == self.dummy_unet.config.sample_size[0]
										    and image.width == self.dummy_unet.config.sample_size[1]
										)
										lowercase_					:			Dict										=       np.frombuffer(image.tobytes()				,			dtype="""uint8"""    )[:10]
										lowercase_					:			Optional[Any]										=       np.frombuffer(image_from_tuple.tobytes()				,			dtype="""uint8"""    )[:10]
										lowercase_					:			Dict										=       np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]    )

										assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0
										assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() == 0

										lowercase_					:			str										=       Mel(
										    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]				,			y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]				,			)

										lowercase_					:			List[Any]										=       DDIMScheduler()
										lowercase_					:			Dict										=       self.dummy_vqvae_and_unet
										lowercase_					:			Tuple										=       AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]				,			unet=dummy_vqvae_and_unet[1]				,			mel=lowercase_				,			scheduler=lowercase_    )
										lowercase_					:			Optional[Any]										=       pipe.to(lowercase_    )
										pipe.set_progress_bar_config(disable=lowercase_    )

										np.random.seed(0    )
										lowercase_					:			Tuple										=       np.random.uniform(-1				,			1				,			((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)    )
										lowercase_					:			Any										=       torch.Generator(device=lowercase_    ).manual_seed(42    )
										lowercase_					:			Optional[int]										=       pipe(raw_audio=lowercase_				,			generator=lowercase_				,			start_step=5				,			steps=10    )
										lowercase_					:			Dict										=       output.images[0]

										assert (
										    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
										    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
										)
										lowercase_					:			List[Any]										=       np.frombuffer(image.tobytes()				,			dtype="""uint8"""    )[:10]
										lowercase_					:			Optional[int]										=       np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]    )

										assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0

										lowercase_					:			Union[str, Any]										=       self.dummy_unet_condition
										lowercase_					:			Any										=       AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]				,			unet=lowercase_				,			mel=lowercase_				,			scheduler=lowercase_    )
										lowercase_					:			Optional[int]										=       pipe.to(lowercase_    )
										pipe.set_progress_bar_config(disable=lowercase_    )

										np.random.seed(0    )
										lowercase_					:			str										=       torch.rand((1, 1, 10)    )
										lowercase_					:			Union[str, Any]										=       pipe(generator=lowercase_				,			encoding=lowercase_    )
										lowercase_					:			Dict										=       output.images[0]
										lowercase_					:			Tuple										=       np.frombuffer(image.tobytes()				,			dtype="""uint8"""    )[:10]
										lowercase_					:			List[str]										=       np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]    )

										assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0





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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[Any]    ):
										lowercase_					:			List[Any]										=       torch_device

										lowercase_					:			Optional[Any]										=       DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256"""    )
										lowercase_					:			int										=       pipe.to(lowercase_    )
										pipe.set_progress_bar_config(disable=lowercase_    )

										lowercase_					:			Optional[int]										=       torch.Generator(device=lowercase_    ).manual_seed(42    )
										lowercase_					:			int										=       pipe(generator=lowercase_    )
										lowercase_					:			Dict										=       output.audios[0]
										lowercase_					:			Tuple										=       output.images[0]

										assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
										assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
										lowercase_					:			Union[str, Any]										=       np.frombuffer(image.tobytes()				,			dtype="""uint8"""    )[:10]
										lowercase_					:			Dict										=       np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]    )

										assert np.abs(image_slice.flatten() - expected_slice    ).max() == 0






'''simple docstring'''




import copy
import os
from typing import Union

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


_lowercase						: Optional[Any]						=						logging.get_logger(__name__)

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





class     __magic_name__						(    _UpperCAmelCase):
			UpperCamelCase__				=       '''altclip_text_model'''







			def __init__(	self				:  Union[str, Any]				,			lowercase_				:  str=250002				,			lowercase_				:  Union[str, Any]=1024				,			lowercase_				:  Any=24				,			lowercase_				:  Union[str, Any]=16				,			lowercase_				:  Any=4096				,			lowercase_				:  Union[str, Any]="gelu"				,			lowercase_				:  Union[str, Any]=0.1				,			lowercase_				:  Union[str, Any]=0.1				,			lowercase_				:  int=514				,			lowercase_				:  Union[str, Any]=1				,			lowercase_				:  List[str]=0.02				,			lowercase_				:  Optional[int]=0.02				,			lowercase_				:  str=1E-05				,			lowercase_				:  List[str]=1				,			lowercase_				:  List[Any]=0				,			lowercase_				:  Dict=2				,			lowercase_				:  Union[str, Any]="absolute"				,			lowercase_				:  Any=True				,			lowercase_				:  Union[str, Any]=768				,			**lowercase_				:  Any				,			):
										super().__init__(pad_token_id=lowercase_				,			bos_token_id=lowercase_				,			eos_token_id=lowercase_				,			**lowercase_    )

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





class     __magic_name__						(    _UpperCAmelCase):
			UpperCamelCase__				=       '''altclip_vision_model'''







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

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







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

										lowercase_						,						lowercase_					:			str										=       cls.get_config_dict(lowercase_				,			**lowercase_    )

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





class     __magic_name__						(    _UpperCAmelCase):
			UpperCamelCase__				=       '''altclip'''
			UpperCamelCase__				=       True







			def __init__(	self				:  Optional[int]				,			lowercase_				:  Dict=None				,			lowercase_				:  List[Any]=None				,			lowercase_				:  Tuple=768				,			lowercase_				:  List[str]=2.65_92				,			**lowercase_				:  List[Any]    ):
										# 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!).
										lowercase_					:			Dict										=       kwargs.pop("""text_config_dict"""				,			lowercase_    )
										lowercase_					:			str										=       kwargs.pop("""vision_config_dict"""				,			lowercase_    )

										super().__init__(**lowercase_    )

										# 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:
																								lowercase_					:			Dict										=       {}

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

            # 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:
																								lowercase_					:			int										=       {}

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

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

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

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

										lowercase_					:			Optional[int]										=       AltCLIPTextConfig(**lowercase_    )
										lowercase_					:			Any										=       AltCLIPVisionConfig(**lowercase_    )

										lowercase_					:			List[Any]										=       projection_dim
										lowercase_					:			Optional[Any]										=       logit_scale_init_value
										lowercase_					:			int										=       1.0







			@classmethod
			def 	SCREAMING_SNAKE_CASE_     (	cls				:  Dict				,			lowercase_				:  AltCLIPTextConfig				,			lowercase_				:  AltCLIPVisionConfig				,			**lowercase_				:  Optional[int]    ):
										return cls(text_config=text_config.to_dict()				,			vision_config=vision_config.to_dict()				,			**lowercase_    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			Union[str, Any]										=       copy.deepcopy(self.__dict__    )
										lowercase_					:			Optional[int]										=       self.text_config.to_dict()
										lowercase_					:			Any										=       self.vision_config.to_dict()
										lowercase_					:			List[str]										=       self.__class__.model_type
										return output





