
'''simple docstring'''







import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class  lowerCAmelCase__   (  __SCREAMING_SNAKE_CASE    ,						unittest.TestCase     ):
					lowerCAmelCase_        =     LDMTextToImagePipeline
					lowerCAmelCase_        =     TEXT_TO_IMAGE_PARAMS - {
					    '''negative_prompt''',
					    '''negative_prompt_embeds''',
					    '''cross_attention_kwargs''',
					    '''prompt_embeds''',
					}
					lowerCAmelCase_        =     PipelineTesterMixin.required_optional_params - {
					    '''num_images_per_prompt''',
					    '''callback''',
					    '''callback_steps''',
					}
					lowerCAmelCase_        =     TEXT_TO_IMAGE_BATCH_PARAMS
					lowerCAmelCase_        =     False






					def 	_snake_case    (   self		):


											"""simple docstring"""





											torch.manual_seed(0		)
											lowercase_	:     Tuple													=       UNetaDConditionModel(
											    block_out_channels=(32, 64)				,							layers_per_block=2				,							sample_size=32				,							in_channels=4				,							out_channels=4				,							down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')				,							up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')				,							cross_attention_dim=32				,							)
											lowercase_	:     Optional[int]													=       DDIMScheduler(
											    beta_start=0.00_085				,							beta_end=0.012				,							beta_schedule='''scaled_linear'''				,							clip_sample=_SCREAMING_SNAKE_CASE				,							set_alpha_to_one=_SCREAMING_SNAKE_CASE				,							)
											torch.manual_seed(0		)
											lowercase_	:     Optional[int]													=       AutoencoderKL(
											    block_out_channels=(32, 64)				,							in_channels=3				,							out_channels=3				,							down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''')				,							up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''')				,							latent_channels=4				,							)
											torch.manual_seed(0		)
											lowercase_	:     List[str]													=       CLIPTextConfig(
											    bos_token_id=0				,							eos_token_id=2				,							hidden_size=32				,							intermediate_size=37				,							layer_norm_eps=1E-0_5				,							num_attention_heads=4				,							num_hidden_layers=5				,							pad_token_id=1				,							vocab_size=10_00				,							)
											lowercase_	:     Optional[int]													=       CLIPTextModel(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[Any]													=       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		)

											lowercase_	:     Optional[Any]													=       {
											    "unet": unet,
											    "scheduler": scheduler,
											    "vqvae": vae,
											    "bert": text_encoder,
											    "tokenizer": tokenizer,
											}
											return components






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE=0		):


											"""simple docstring"""





											if str(_SCREAMING_SNAKE_CASE		).startswith('''mps'''		):
																	lowercase_	:     Union[str, Any]													=       torch.manual_seed(_SCREAMING_SNAKE_CASE		)
											else:
																	lowercase_	:     Optional[Any]													=       torch.Generator(device=_SCREAMING_SNAKE_CASE		).manual_seed(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Any													=       {
											    "prompt": "A painting of a squirrel eating a burger",
											    "generator": generator,
											    "num_inference_steps": 2,
											    "guidance_scale": 6.0,
											    "output_type": "numpy",
											}
											return inputs






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Any													=       "cpu"  # ensure determinism for the device-dependent torch.Generator

											lowercase_	:     Optional[int]													=       self.get_dummy_components()
											lowercase_	:     List[Any]													=       LDMTextToImagePipeline(**_SCREAMING_SNAKE_CASE		)
											pipe.to(_SCREAMING_SNAKE_CASE		)
											pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

											lowercase_	:     Any													=       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       pipe(**_SCREAMING_SNAKE_CASE		).images
											lowercase_	:     List[str]													=       image[0, -3:, -3:, -1]

											assert image.shape == (1, 16, 16, 3)
											lowercase_	:     List[str]													=       np.array([0.6_101, 0.6_156, 0.5_622, 0.4_895, 0.6_661, 0.3_804, 0.5_748, 0.6_136, 0.5_014]		)

											assert np.abs(image_slice.flatten() - expected_slice		).max() < 1E-3







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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE=torch.floataa				,							__SCREAMING_SNAKE_CASE=0		):


											"""simple docstring"""





											lowercase_	:     List[Any]													=       torch.manual_seed(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     str													=       np.random.RandomState(_SCREAMING_SNAKE_CASE		).standard_normal((1, 4, 32, 32)		)
											lowercase_	:     Union[str, Any]													=       torch.from_numpy(_SCREAMING_SNAKE_CASE		).to(device=_SCREAMING_SNAKE_CASE				,							dtype=_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       {
											    "prompt": "A painting of a squirrel eating a burger",
											    "latents": latents,
											    "generator": generator,
											    "num_inference_steps": 3,
											    "guidance_scale": 6.0,
											    "output_type": "numpy",
											}
											return inputs






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''		).to(_SCREAMING_SNAKE_CASE		)
											pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

											lowercase_	:     Tuple													=       self.get_inputs(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       pipe(**_SCREAMING_SNAKE_CASE		).images
											lowercase_	:     Tuple													=       image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 2_56, 2_56, 3)
											lowercase_	:     Any													=       np.array([0.51_825, 0.52_850, 0.52_543, 0.54_258, 0.52_304, 0.52_569, 0.54_363, 0.55_276, 0.56_878]		)
											lowercase_	:     Union[str, Any]													=       np.abs(expected_slice - image_slice		).max()
											assert max_diff < 1E-3







@nightly
@require_torch_gpu
class  lowerCAmelCase__   (  unittest.TestCase     ):






					def 	_snake_case    (   self		):


											"""simple docstring"""





											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE=torch.floataa				,							__SCREAMING_SNAKE_CASE=0		):


											"""simple docstring"""





											lowercase_	:     int													=       torch.manual_seed(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       np.random.RandomState(_SCREAMING_SNAKE_CASE		).standard_normal((1, 4, 32, 32)		)
											lowercase_	:     List[Any]													=       torch.from_numpy(_SCREAMING_SNAKE_CASE		).to(device=_SCREAMING_SNAKE_CASE				,							dtype=_SCREAMING_SNAKE_CASE		)
											lowercase_	:     int													=       {
											    "prompt": "A painting of a squirrel eating a burger",
											    "latents": latents,
											    "generator": generator,
											    "num_inference_steps": 50,
											    "guidance_scale": 6.0,
											    "output_type": "numpy",
											}
											return inputs






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''		).to(_SCREAMING_SNAKE_CASE		)
											pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)

											lowercase_	:     int													=       self.get_inputs(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       pipe(**_SCREAMING_SNAKE_CASE		).images[0]

											lowercase_	:     int													=       load_numpy(
											    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''		)
											lowercase_	:     Optional[int]													=       np.abs(expected_image - image		).max()
											assert max_diff < 1E-3








"""simple docstring"""






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


__snake_case							:   List[Any]      =    logging.get_logger(__name__)

__snake_case							:   Any      =    {
    'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json',
    # See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}



class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	'mctct'

	def __init__(     self:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		str=8065       ,			_SCREAMING_SNAKE_CASE:		str=1536       ,			_SCREAMING_SNAKE_CASE:		str=36       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=6144       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=4       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=384       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=920       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=1e-5       ,			_SCREAMING_SNAKE_CASE:		List[Any]=0.3       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]="relu"       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=0.02       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=0.3       ,			_SCREAMING_SNAKE_CASE:		Dict=0.3       ,			_SCREAMING_SNAKE_CASE:		List[Any]=1       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=0       ,			_SCREAMING_SNAKE_CASE:		List[str]=2       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=1       ,			_SCREAMING_SNAKE_CASE:		Tuple=0.3       ,			_SCREAMING_SNAKE_CASE:		Dict=1       ,			_SCREAMING_SNAKE_CASE:		int=(7,)       ,			_SCREAMING_SNAKE_CASE:		str=(3,)       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=80       ,			_SCREAMING_SNAKE_CASE:		Tuple=1       ,			_SCREAMING_SNAKE_CASE:		Dict=None       ,			_SCREAMING_SNAKE_CASE:		Tuple="sum"       ,			_SCREAMING_SNAKE_CASE:		List[str]=False       ,			**_SCREAMING_SNAKE_CASE:		Tuple       ,			)				->       Tuple:

				"""simple docstring"""

				super().__init__(**_SCREAMING_SNAKE_CASE       ,			pad_token_id=_SCREAMING_SNAKE_CASE       ,			bos_token_id=_SCREAMING_SNAKE_CASE       ,			eos_token_id=_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  str												=       vocab_size
				__lowerCAmelCase      :  str												=       hidden_size
				__lowerCAmelCase      :  str												=       num_hidden_layers
				__lowerCAmelCase      :  str												=       intermediate_size
				__lowerCAmelCase      :  List[Any]												=       num_attention_heads
				__lowerCAmelCase      :  Dict												=       attention_head_dim
				__lowerCAmelCase      :  Optional[int]												=       max_position_embeddings
				__lowerCAmelCase      :  str												=       layer_norm_eps
				__lowerCAmelCase      :  Tuple												=       layerdrop
				__lowerCAmelCase      :  str												=       hidden_act
				__lowerCAmelCase      :  List[Any]												=       initializer_range
				__lowerCAmelCase      :  int												=       hidden_dropout_prob
				__lowerCAmelCase      :  Optional[Any]												=       attention_probs_dropout_prob
				__lowerCAmelCase      :  str												=       pad_token_id
				__lowerCAmelCase      :  Optional[int]												=       bos_token_id
				__lowerCAmelCase      :  Union[str, Any]												=       eos_token_id
				__lowerCAmelCase      :  Any												=       conv_glu_dim
				__lowerCAmelCase      :  Optional[int]												=       conv_dropout
				__lowerCAmelCase      :  Union[str, Any]												=       num_conv_layers
				__lowerCAmelCase      :  Optional[int]												=       input_feat_per_channel
				__lowerCAmelCase      :  Union[str, Any]												=       input_channels
				__lowerCAmelCase      :  Optional[Any]												=       conv_channels
				__lowerCAmelCase      :  Dict												=       ctc_loss_reduction
				__lowerCAmelCase      :  int												=       ctc_zero_infinity

				# prevents config testing fail with exporting to json
				__lowerCAmelCase      :  List[str]												=       list(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Dict												=       list(_SCREAMING_SNAKE_CASE)

				if len(self.conv_kernel) != self.num_conv_layers:
							raise ValueError(
							    "Configuration for convolutional module is incorrect. "
							    "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` "
							    F"""but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, """
							    F"""`config.num_conv_layers = {self.num_conv_layers}`.""")