






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_       (				__snake_case     ,    unittest.TestCase					):
							UpperCamelCase_		:List[Any]		      =    LDMTextToImagePipeline
							UpperCamelCase_		:Union[str, Any]		      =    TEXT_TO_IMAGE_PARAMS - {
							    'negative_prompt',
							    'negative_prompt_embeds',
							    'cross_attention_kwargs',
							    'prompt_embeds',
							}
							UpperCamelCase_		:List[str]		      =    PipelineTesterMixin.required_optional_params - {
							    'num_images_per_prompt',
							    'callback',
							    'callback_steps',
							}
							UpperCamelCase_		:Optional[Any]		      =    TEXT_TO_IMAGE_BATCH_PARAMS
							UpperCamelCase_		:Optional[int]		      =    False




							def 						__snake_case					(   self     :   Any	):
											torch.manual_seed(0	)
											lowerCAmelCase__      			=						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 ,							)
											lowerCAmelCase__      			=						DDIMScheduler(
											    beta_start=0.00_085 ,							beta_end=0.012 ,							beta_schedule='''scaled_linear''' ,							clip_sample=_lowercase ,							set_alpha_to_one=_lowercase ,							)
											torch.manual_seed(0	)
											lowerCAmelCase__      			=						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	)
											lowerCAmelCase__      			=						CLIPTextConfig(
											    bos_token_id=0 ,							eos_token_id=2 ,							hidden_size=32 ,							intermediate_size=37 ,							layer_norm_eps=1e-05 ,							num_attention_heads=4 ,							num_hidden_layers=5 ,							pad_token_id=1 ,							vocab_size=1_000 ,							)
											lowerCAmelCase__      			=						CLIPTextModel(_lowercase	)
											lowerCAmelCase__      			=						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''	)

											lowerCAmelCase__      			=						{
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vqvae""": vae,
											    """bert""": text_encoder,
											    """tokenizer""": tokenizer,
											}
											return components




							def 						__snake_case					(   self     :   Union[str, Any] ,							SCREAMING_SNAKE_CASE_     :   Tuple ,							SCREAMING_SNAKE_CASE_     :   List[Any]=0	):

											if str(_lowercase	).startswith('''mps'''	):
															lowerCAmelCase__      			=						torch.manual_seed(_lowercase	)
											else:
															lowerCAmelCase__      			=						torch.Generator(device=_lowercase	).manual_seed(_lowercase	)
											lowerCAmelCase__      			=						{
											    """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     :   List[Any]	):
											lowerCAmelCase__      			=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator

											lowerCAmelCase__      			=						self.get_dummy_components()
											lowerCAmelCase__      			=						LDMTextToImagePipeline(**_lowercase	)
											pipe.to(_lowercase	)
											pipe.set_progress_bar_config(disable=_lowercase	)

											lowerCAmelCase__      			=						self.get_dummy_inputs(_lowercase	)
											lowerCAmelCase__      			=						pipe(**_lowercase	).images
											lowerCAmelCase__      			=						image[0, -3:, -3:, -1]

											assert image.shape == (1, 16, 16, 3)
											lowerCAmelCase__      			=						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     :   Optional[int]	):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




							def 						__snake_case					(   self     :   List[str] ,							SCREAMING_SNAKE_CASE_     :   Union[str, Any] ,							SCREAMING_SNAKE_CASE_     :   Any=torch.floataa ,							SCREAMING_SNAKE_CASE_     :   Tuple=0	):
											lowerCAmelCase__      			=						torch.manual_seed(_lowercase	)
											lowerCAmelCase__      			=						np.random.RandomState(_lowercase	).standard_normal((1, 4, 32, 32)	)
											lowerCAmelCase__      			=						torch.from_numpy(_lowercase	).to(device=_lowercase ,							dtype=_lowercase	)
											lowerCAmelCase__      			=						{
											    """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     :   int	):
											lowerCAmelCase__      			=						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''	).to(_lowercase	)
											pipe.set_progress_bar_config(disable=_lowercase	)

											lowerCAmelCase__      			=						self.get_inputs(_lowercase	)
											lowerCAmelCase__      			=						pipe(**_lowercase	).images
											lowerCAmelCase__      			=						image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 256, 256, 3)
											lowerCAmelCase__      			=						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]	)
											lowerCAmelCase__      			=						np.abs(expected_slice - image_slice	).max()
											assert max_diff < 1e-3



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




							def 						__snake_case					(   self     :   Tuple	):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




							def 						__snake_case					(   self     :   str ,							SCREAMING_SNAKE_CASE_     :   Optional[int] ,							SCREAMING_SNAKE_CASE_     :   List[str]=torch.floataa ,							SCREAMING_SNAKE_CASE_     :   Optional[int]=0	):
											lowerCAmelCase__      			=						torch.manual_seed(_lowercase	)
											lowerCAmelCase__      			=						np.random.RandomState(_lowercase	).standard_normal((1, 4, 32, 32)	)
											lowerCAmelCase__      			=						torch.from_numpy(_lowercase	).to(device=_lowercase ,							dtype=_lowercase	)
											lowerCAmelCase__      			=						{
											    """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     :   Union[str, Any]	):
											lowerCAmelCase__      			=						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''	).to(_lowercase	)
											pipe.set_progress_bar_config(disable=_lowercase	)

											lowerCAmelCase__      			=						self.get_inputs(_lowercase	)
											lowerCAmelCase__      			=						pipe(**_lowercase	).images[0]

											lowerCAmelCase__      			=						load_numpy(
											    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''	)
											lowerCAmelCase__      			=						np.abs(expected_image - image	).max()
											assert max_diff < 1e-3










from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_UpperCAmelCase			:		str   				=    {
    "configuration_blenderbot_small": [
        "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlenderbotSmallConfig",
        "BlenderbotSmallOnnxConfig",
    ],
    "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"],
}

try:
			if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_UpperCAmelCase			:		List[str]   				=    ["BlenderbotSmallTokenizerFast"]

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_UpperCAmelCase			:		List[str]   				=    [
			    "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST",
			    "BlenderbotSmallForCausalLM",
			    "BlenderbotSmallForConditionalGeneration",
			    "BlenderbotSmallModel",
			    "BlenderbotSmallPreTrainedModel",
			]

try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_UpperCAmelCase			:		Dict   				=    [
			    "TFBlenderbotSmallForConditionalGeneration",
			    "TFBlenderbotSmallModel",
			    "TFBlenderbotSmallPreTrainedModel",
			]

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			_UpperCAmelCase			:		List[str]   				=    [
			    "FlaxBlenderbotSmallForConditionalGeneration",
			    "FlaxBlenderbotSmallModel",
			    "FlaxBlenderbotSmallPreTrainedModel",
			]

if TYPE_CHECKING:
			from .configuration_blenderbot_small import (
			    BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP,
			    BlenderbotSmallConfig,
			    BlenderbotSmallOnnxConfig,
			)
			from .tokenization_blenderbot_small import BlenderbotSmallTokenizer

			try:
						if not is_tokenizers_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_blenderbot_small import (
						    BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST,
						    BlenderbotSmallForCausalLM,
						    BlenderbotSmallForConditionalGeneration,
						    BlenderbotSmallModel,
						    BlenderbotSmallPreTrainedModel,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_blenderbot_small import (
						    TFBlenderbotSmallForConditionalGeneration,
						    TFBlenderbotSmallModel,
						    TFBlenderbotSmallPreTrainedModel,
						)

			try:
						if not is_flax_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_flax_blenderbot_small import (
						    FlaxBlenderbotSmallForConditionalGeneration,
						    FlaxBlenderbotSmallModel,
						    FlaxBlenderbotSmallPreTrainedModel,
						)

else:
			import sys

			_UpperCAmelCase			:		int   				=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





