


'''simple docstring'''


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

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


enable_full_determinism()





class    lowercase__  (						_snake_case					,					_snake_case					,					unittest.TestCase ):





							'''simple docstring'''


							A_							:				Optional[int]				     =  StableDiffusionParadigmsPipeline
							A_							:				Union[str, Any]				     =  TEXT_TO_IMAGE_PARAMS
							A_							:				List[str]				     =  TEXT_TO_IMAGE_BATCH_PARAMS
							A_							:				int				     =  TEXT_TO_IMAGE_IMAGE_PARAMS
							A_							:				str				     =  TEXT_TO_IMAGE_IMAGE_PARAMS






							def UpperCAmelCase_     (   self  ):
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE			:	List[str]							=				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   , attention_head_dim=(2, 4)   , use_linear_projection=__snake_case   , )
											_SCREAMING_SNAKE_CASE			:	int							=				DDIMParallelScheduler(
											    beta_start=0.00085   , beta_end=0.012   , beta_schedule="""scaled_linear"""   , clip_sample=__snake_case   , set_alpha_to_one=__snake_case   , )
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE			:	str							=				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   , sample_size=128   , )
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE			:	Any							=				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=1000   , hidden_act="""gelu"""   , projection_dim=512   , )
											_SCREAMING_SNAKE_CASE			:	Dict							=				CLIPTextModel(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""  )

											_SCREAMING_SNAKE_CASE			:	List[str]							=				{
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vae""": vae,
											    """text_encoder""": text_encoder,
											    """tokenizer""": tokenizer,
											    """safety_checker""": None,
											    """feature_extractor""": None,
											}
											return components






							def UpperCAmelCase_     (   self   , __snake_case   , __snake_case=0  ):
											if str(__snake_case  ).startswith("""mps"""  ):
															_SCREAMING_SNAKE_CASE			:	str							=				torch.manual_seed(__snake_case  )
											else:
															_SCREAMING_SNAKE_CASE			:	int							=				torch.Generator(device=__snake_case  ).manual_seed(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				{
											    """prompt""": """a photograph of an astronaut riding a horse""",
											    """generator""": generator,
											    """num_inference_steps""": 10,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											    """parallel""": 3,
											    """debug""": True,
											}
											return inputs






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Dict							=				"""cpu"""  # ensure determinism for the device-dependent torch.Generator
											_SCREAMING_SNAKE_CASE			:	Tuple							=				self.get_dummy_components()
											_SCREAMING_SNAKE_CASE			:	Tuple							=				StableDiffusionParadigmsPipeline(**__snake_case  )
											_SCREAMING_SNAKE_CASE			:	str							=				sd_pipe.to(__snake_case  )
											sd_pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.get_dummy_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				sd_pipe(**__snake_case  ).images
											_SCREAMING_SNAKE_CASE			:	List[str]							=				image[0, -3:, -3:, -1]
											assert image.shape == (1, 64, 64, 3)

											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				np.array([0.4773, 0.5417, 0.4723, 0.4925, 0.5631, 0.4752, 0.5240, 0.4935, 0.5023]  )

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






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				"""cpu"""  # ensure determinism for the device-dependent torch.Generator
											_SCREAMING_SNAKE_CASE			:	str							=				self.get_dummy_components()
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				DDPMParallelScheduler()
											torch.manual_seed(0  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				StableDiffusionParadigmsPipeline(**__snake_case  )
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				sd_pipe.to(__snake_case  )
											sd_pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				self.get_dummy_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	str							=				sd_pipe(**__snake_case  ).images
											_SCREAMING_SNAKE_CASE			:	Any							=				image[0, -3:, -3:, -1]
											assert image.shape == (1, 64, 64, 3)

											_SCREAMING_SNAKE_CASE			:	str							=				np.array([0.3573, 0.4420, 0.4960, 0.4799, 0.3796, 0.3879, 0.4819, 0.4365, 0.4468]  )

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






							def UpperCAmelCase_     (   self  ):
											super().test_inference_batch_consistent(batch_sizes=[1, 2]  )






							def UpperCAmelCase_     (   self  ):
											super().test_inference_batch_single_identical(batch_size=2   , expected_max_diff=3e-3  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				"""cpu"""  # ensure determinism for the device-dependent torch.Generator
											_SCREAMING_SNAKE_CASE			:	Any							=				self.get_dummy_components()
											_SCREAMING_SNAKE_CASE			:	int							=				StableDiffusionParadigmsPipeline(**__snake_case  )
											_SCREAMING_SNAKE_CASE			:	str							=				sd_pipe.to(__snake_case  )
											sd_pipe.set_progress_bar_config(disable=__snake_case  )

											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				self.get_dummy_inputs(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	int							=				"""french fries"""
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				sd_pipe(**__snake_case   , negative_prompt=__snake_case  )
											_SCREAMING_SNAKE_CASE			:	int							=				output.images
											_SCREAMING_SNAKE_CASE			:	Tuple							=				image[0, -3:, -3:, -1]

											assert image.shape == (1, 64, 64, 3)

											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				np.array([0.4771, 0.5420, 0.4683, 0.4918, 0.5636, 0.4725, 0.5230, 0.4923, 0.5015]  )

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





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





							'''simple docstring'''


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






							def UpperCAmelCase_     (   self   , __snake_case=0  ):
											_SCREAMING_SNAKE_CASE			:	Any							=				torch.Generator(device=__snake_case  ).manual_seed(__snake_case  )
											_SCREAMING_SNAKE_CASE			:	Dict							=				{
											    """prompt""": """a photograph of an astronaut riding a horse""",
											    """generator""": generator,
											    """num_inference_steps""": 10,
											    """guidance_scale""": 7.5,
											    """output_type""": """numpy""",
											    """parallel""": 3,
											    """debug""": True,
											}
											return inputs






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Any							=				"""stabilityai/stable-diffusion-2-base"""
											_SCREAMING_SNAKE_CASE			:	List[str]							=				DDIMParallelScheduler.from_pretrained(__snake_case   , subfolder="""scheduler"""  )
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				StableDiffusionParadigmsPipeline.from_pretrained(__snake_case   , scheduler=__snake_case   , safety_checker=__snake_case  )
											pipe.to(__snake_case  )
											pipe.set_progress_bar_config(disable=__snake_case  )
											pipe.enable_attention_slicing()

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

											assert image.shape == (1, 512, 512, 3)

											_SCREAMING_SNAKE_CASE			:	List[str]							=				np.array([0.9622, 0.9602, 0.9748, 0.9591, 0.9630, 0.9691, 0.9661, 0.9631, 0.9741]  )

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








'''simple docstring'''


import os
import tempfile
import unittest
from typing import List

from transformers.models.esm.tokenization_esm import VOCAB_FILES_NAMES, EsmTokenizer
from transformers.testing_utils import require_tokenizers
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.tokenization_utils_base import PreTrainedTokenizerBase





@require_tokenizers
class    lowercase__  (						unittest.TestCase ):





							'''simple docstring'''


							A_							:				Optional[Any]				     =  EsmTokenizer






							def UpperCAmelCase_     (   self  ):
											super().setUp()
											_SCREAMING_SNAKE_CASE			:	List[Any]							=				tempfile.mkdtemp()
											# fmt: off
											_SCREAMING_SNAKE_CASE			:	List[str]							=				["<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>"]  # noqa: E501
											# fmt: on
											_SCREAMING_SNAKE_CASE			:	Any							=				os.path.join(self.tmpdirname   , VOCAB_FILES_NAMES["""vocab_file"""]  )
											with open(self.vocab_file   , """w"""   , encoding="""utf-8"""  ) as vocab_writer:
															vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]  )  )






							def UpperCAmelCase_     (   self   , **__snake_case  ):
											return [self.get_tokenizer(**__snake_case  )]






							def UpperCAmelCase_     (   self   , **__snake_case  ):
											return self.tokenizer_class.from_pretrained(self.tmpdirname   , **__snake_case  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	List[str]							=				self.tokenizer_class(self.vocab_file  )

											_SCREAMING_SNAKE_CASE			:	int							=				tokenizer.tokenize("""LAGVS"""  )
											self.assertListEqual(__snake_case   , ["""L""", """A""", """G""", """V""", """S"""]  )
											self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case  )   , [4, 5, 6, 7, 8]  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	int							=				self.tokenizer_class(self.vocab_file  )

											_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				"""LAGVS"""
											self.assertListEqual(tokenizer.encode(__snake_case  )   , [0, 4, 5, 6, 7, 8, 2]  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Any							=				self.tokenizer_class(self.vocab_file  )

											_SCREAMING_SNAKE_CASE			:	List[Any]							=				["""LAGVS""", """WCB"""]
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				tokenizer(__snake_case   , padding=__snake_case  )["""input_ids"""]

											self.assertListEqual(__snake_case   , [[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2]]  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				self.tokenizer_class(self.vocab_file  )

											_SCREAMING_SNAKE_CASE			:	str							=				["""LAGVS""", """WCB"""]
											_SCREAMING_SNAKE_CASE			:	Optional[int]							=				tokenizer(__snake_case   , padding=__snake_case  )["""input_ids"""]

											self.assertListEqual(__snake_case   , [[0, 4, 5, 6, 7, 8, 2], [0, 22, 23, 25, 2, 1, 1]]  )






							def UpperCAmelCase_     (   self  ):
											_SCREAMING_SNAKE_CASE			:	str							=				self.get_tokenizers(fast=__snake_case  )
											for tokenizer in tokenizers:
															with self.subTest(f"""{tokenizer.__class__.__name__}"""  ):
																			_SCREAMING_SNAKE_CASE			:	Optional[int]							=				"""<unk>"""
																			_SCREAMING_SNAKE_CASE			:	Optional[int]							=				"""<mask>"""

																			_SCREAMING_SNAKE_CASE			:	Union[str, Any]							=				tokenizer.tokenize(__snake_case  )
																			_SCREAMING_SNAKE_CASE			:	Optional[Any]							=				tokenizer.tokenize(__snake_case  )

																			self.assertEqual(len(__snake_case  )   , 1  )
																			self.assertEqual(len(__snake_case  )   , 1  )
																			self.assertEqual(token_a[0]   , __snake_case  )
																			self.assertEqual(token_a[0]   , __snake_case  )




