





'''simple docstring'''







import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class 					__a      (lowerCamelCase       ,		lowerCamelCase       ,		unittest.TestCase     ):
							__a					:   List[str]									=       StableDiffusionXLImgaImgPipeline
							__a					:   Union[str, Any]									=       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
							__a					:   List[str]									=       PipelineTesterMixin.required_optional_params - {"latents"}
							__a					:   Optional[Any]									=       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							__a					:   Optional[int]									=       IMAGE_TO_IMAGE_IMAGE_PARAMS
							__a					:   str									=       IMAGE_TO_IMAGE_IMAGE_PARAMS

							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       List[Any]:







													"""simple docstring"""
													torch.manual_seed(0   )
													UpperCAmelCase_			:      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''')       ,     attention_head_dim=(2, 4)       ,     use_linear_projection=__lowerCAmelCase       ,     addition_embed_type='''text_time'''       ,     addition_time_embed_dim=8       ,     transformer_layers_per_block=(1, 2)       ,     projection_class_embeddings_input_dim=80       ,     cross_attention_dim=64       ,     )
													UpperCAmelCase_			:      List[Any]     						=  EulerDiscreteScheduler(
													    beta_start=0.0_0_0_8_5       ,     beta_end=0.0_1_2       ,     steps_offset=1       ,     beta_schedule='''scaled_linear'''       ,     timestep_spacing='''leading'''       ,     )
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Union[str, Any]     						=  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=1_28       ,     )
													torch.manual_seed(0   )
													UpperCAmelCase_			:      Union[str, 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=10_00       ,     hidden_act='''gelu'''       ,     projection_dim=32       ,     )
													UpperCAmelCase_			:      int     						=  CLIPTextModel(__lowerCAmelCase   )
													UpperCAmelCase_			:      str     						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       ,     local_files_only=__lowerCAmelCase   )

													UpperCAmelCase_			:      Optional[Any]     						=  CLIPTextModelWithProjection(__lowerCAmelCase   )
													UpperCAmelCase_			:      Any     						=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       ,     local_files_only=__lowerCAmelCase   )

													UpperCAmelCase_			:      List[str]     						=  {
													    '''unet''': unet,
													    '''scheduler''': scheduler,
													    '''vae''': vae,
													    '''text_encoder''': text_encoder,
													    '''tokenizer''': tokenizer,
													    '''text_encoder_2''': text_encoder_a,
													    '''tokenizer_2''': tokenizer_a,
													    # "safety_checker": None,
													    # "feature_extractor": None,
													}
													return components

							def     UpperCAmelCase__	(							self							:     Dict       ,     __magic_name__							:     str       ,     __magic_name__							:     List[str]=0   )					->       List[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  floats_tensor((1, 3, 32, 32)       ,     rng=random.Random(__lowerCAmelCase   )   ).to(__lowerCAmelCase   )
													UpperCAmelCase_			:      int     						=  image / 2 + 0.5
													if str(__lowerCAmelCase   ).startswith('''mps'''   ):
																			UpperCAmelCase_			:      List[Any]     						=  torch.manual_seed(__lowerCAmelCase   )
													else:
																			UpperCAmelCase_			:      str     						=  torch.Generator(device=__lowerCAmelCase   ).manual_seed(__lowerCAmelCase   )
													UpperCAmelCase_			:      str     						=  {
													    '''prompt''': '''A painting of a squirrel eating a burger''',
													    '''image''': image,
													    '''generator''': generator,
													    '''num_inference_steps''': 2,
													    '''guidance_scale''': 5.0,
													    '''output_type''': '''numpy''',
													    '''strength''': 0.7_5,
													}
													return inputs

							def     UpperCAmelCase__	(							self							:     Any   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													UpperCAmelCase_			:      List[Any]     						=  self.get_dummy_components()
													UpperCAmelCase_			:      Optional[int]     						=  StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase   )
													UpperCAmelCase_			:      List[Any]     						=  sd_pipe.to(__lowerCAmelCase   )
													sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

													UpperCAmelCase_			:      int     						=  self.get_dummy_inputs(__lowerCAmelCase   )
													UpperCAmelCase_			:      int     						=  sd_pipe(**__lowerCAmelCase   ).images
													UpperCAmelCase_			:      Union[str, Any]     						=  image[0, -3:, -3:, -1]

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

													UpperCAmelCase_			:      str     						=  np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5]   )

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

							def     UpperCAmelCase__	(							self							:     Tuple   )					->       Any:







													"""simple docstring"""
													super().test_attention_slicing_forward_pass(expected_max_diff=3E-3   )

							def     UpperCAmelCase__	(							self							:     Dict   )					->       str:







													"""simple docstring"""
													super().test_inference_batch_single_identical(expected_max_diff=3E-3   )

							def     UpperCAmelCase__	(							self							:     Optional[Any]   )					->       str:







													"""simple docstring"""
													pass



							def     UpperCAmelCase__	(							self							:     Union[str, Any]   )					->       Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Any     						=  self.get_dummy_components()
													UpperCAmelCase_			:      str     						=  StableDiffusionXLImgaImgPipeline(**__lowerCAmelCase   )
													UpperCAmelCase_			:      Optional[Any]     						=  sd_pipe.to(__lowerCAmelCase   )
													UpperCAmelCase_			:      List[str]     						=  sd_pipe.to(__lowerCAmelCase   )
													sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

													# forward without prompt embeds
													UpperCAmelCase_			:      Any     						=  self.get_dummy_inputs(__lowerCAmelCase   )
													UpperCAmelCase_			:      str     						=  3 * ['''this is a negative prompt''']
													UpperCAmelCase_			:      Optional[Any]     						=  negative_prompt
													UpperCAmelCase_			:      str     						=  3 * [inputs['''prompt''']]

													UpperCAmelCase_			:      Any     						=  sd_pipe(**__lowerCAmelCase   )
													UpperCAmelCase_			:      Optional[int]     						=  output.images[0, -3:, -3:, -1]

													# forward with prompt embeds
													UpperCAmelCase_			:      Any     						=  self.get_dummy_inputs(__lowerCAmelCase   )
													UpperCAmelCase_			:      str     						=  3 * ['''this is a negative prompt''']
													UpperCAmelCase_			:      int     						=  3 * [inputs.pop('''prompt'''   )]

													(
													    (
													    UpperCAmelCase_			
													)						,       (
													    UpperCAmelCase_			
													)						,       (
													    UpperCAmelCase_			
													)						,       (
													    UpperCAmelCase_			
													)						,       			
													)			:      int     						=  sd_pipe.encode_prompt(__lowerCAmelCase       ,     negative_prompt=__lowerCAmelCase   )

													UpperCAmelCase_			:      Any     						=  sd_pipe(
													    **__lowerCAmelCase       ,     prompt_embeds=__lowerCAmelCase       ,     negative_prompt_embeds=__lowerCAmelCase       ,     pooled_prompt_embeds=__lowerCAmelCase       ,     negative_pooled_prompt_embeds=__lowerCAmelCase       ,     )
													UpperCAmelCase_			:      List[Any]     						=  output.images[0, -3:, -3:, -1]

													# make sure that it's equal
													assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()   ).max() < 1E-4





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

							def     UpperCAmelCase__	(							self							:     Optional[int]   )					->       Optional[Any]:







													"""simple docstring"""
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()

							def     UpperCAmelCase__	(							self							:     str       ,     __magic_name__							:     List[Any]       ,     __magic_name__							:     int="cpu"       ,     __magic_name__							:     Tuple=torch.floataa       ,     __magic_name__							:     int=0   )					->       Tuple:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  torch.Generator(device=__lowerCAmelCase   ).manual_seed(__lowerCAmelCase   )
													UpperCAmelCase_			:      Tuple     						=  np.random.RandomState(__lowerCAmelCase   ).standard_normal((1, 4, 64, 64)   )
													UpperCAmelCase_			:      Optional[int]     						=  torch.from_numpy(__lowerCAmelCase   ).to(device=__lowerCAmelCase       ,     dtype=__lowerCAmelCase   )
													UpperCAmelCase_			:      int     						=  {
													    '''prompt''': '''a photograph of an astronaut riding a horse''',
													    '''latents''': latents,
													    '''generator''': generator,
													    '''num_inference_steps''': 3,
													    '''guidance_scale''': 7.5,
													    '''output_type''': '''numpy''',
													}
													return inputs



							def     UpperCAmelCase__	(							self							:     Dict   )					->       List[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      Tuple     						=  DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''   )
													pipe.to(__lowerCAmelCase   )
													pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

													UpperCAmelCase_			:      Optional[int]     						=  self.get_inputs(__lowerCAmelCase   )
													UpperCAmelCase_			:      Optional[Any]     						=  pipe(**__lowerCAmelCase   ).images
													UpperCAmelCase_			:      int     						=  image[0, -3:, -3:, -1].flatten()

													assert image.shape == (1, 5_12, 5_12, 3)
													UpperCAmelCase_			:      str     						=  np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6]   )
													assert np.abs(image_slice - expected_slice   ).max() < 7E-3












'''simple docstring'''







import json
import os
import unittest

from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
    VOCAB_FILES_NAMES,
    BlenderbotSmallTokenizer,
)

from ...test_tokenization_common import TokenizerTesterMixin


class 					__a      (lowerCamelCase       ,		unittest.TestCase     ):
							__a					:   List[str]									=       BlenderbotSmallTokenizer
							__a					:   List[Any]									=       False

							def     UpperCAmelCase__	(							self							:     str   )					->       str:







													"""simple docstring"""
													super().setUp()

													UpperCAmelCase_			:      Tuple     						=  ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__''']
													UpperCAmelCase_			:      Optional[Any]     						=  dict(zip(__magic_name__       ,     range(len(__magic_name__   )   )   )   )

													UpperCAmelCase_			:      int     						=  ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', '''''']
													UpperCAmelCase_			:      Optional[Any]     						=  {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''}

													UpperCAmelCase_			:      Tuple     						=  os.path.join(self.tmpdirname       ,     VOCAB_FILES_NAMES['''vocab_file''']   )
													UpperCAmelCase_			:      Dict     						=  os.path.join(self.tmpdirname       ,     VOCAB_FILES_NAMES['''merges_file''']   )
													with open(self.vocab_file       ,     '''w'''       ,     encoding='''utf-8'''   ) as fp:
																			fp.write(json.dumps(__magic_name__   ) + '''\n'''   )
													with open(self.merges_file       ,     '''w'''       ,     encoding='''utf-8'''   ) as fp:
																			fp.write('''\n'''.join(__magic_name__   )   )

							def     UpperCAmelCase__	(							self							:     List[Any]       ,     **__magic_name__							:     Dict   )					->       Tuple:







													"""simple docstring"""
													kwargs.update(self.special_tokens_map   )
													return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname       ,     **__magic_name__   )

							def     UpperCAmelCase__	(							self							:     Optional[int]       ,     __magic_name__							:     List[str]   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  '''adapt act apte'''
													UpperCAmelCase_			:      Tuple     						=  '''adapt act apte'''
													return input_text, output_text

							def     UpperCAmelCase__	(							self							:     str   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  BlenderbotSmallTokenizer(self.vocab_file       ,     self.merges_file       ,     **self.special_tokens_map   )
													UpperCAmelCase_			:      List[Any]     						=  '''adapt act apte'''
													UpperCAmelCase_			:      Dict     						=  ['''adapt''', '''act''', '''ap@@''', '''te''']
													UpperCAmelCase_			:      Dict     						=  tokenizer.tokenize(__magic_name__   )
													self.assertListEqual(__magic_name__       ,     __magic_name__   )

													UpperCAmelCase_			:      Tuple     						=  [tokenizer.bos_token] + tokens + [tokenizer.eos_token]

													UpperCAmelCase_			:      Dict     						=  [0, 1, 2, 3, 4, 5]
													self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__   )       ,     __magic_name__   )

							def     UpperCAmelCase__	(							self							:     int   )					->       List[str]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M'''   )
													assert tok('''sam'''   ).input_ids == [13_84]
													UpperCAmelCase_			:      Optional[int]     						=  '''I am a small frog.'''
													UpperCAmelCase_			:      List[str]     						=  tok([src_text]       ,     padding=__magic_name__       ,     truncation=__magic_name__   )['''input_ids''']
													UpperCAmelCase_			:      Dict     						=  tok.batch_decode(__magic_name__       ,     skip_special_tokens=__magic_name__       ,     clean_up_tokenization_spaces=__magic_name__   )[0]
													assert src_text != decoded  # I wish it did!
													assert decoded == "i am a small frog ."



							def     UpperCAmelCase__	(							self							:     Any   )					->       Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      int     						=  BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M'''   )
													UpperCAmelCase_			:      List[Any]     						=  '''I am a small frog .'''
													UpperCAmelCase_			:      Any     						=  '''.'''
													UpperCAmelCase_			:      List[Any]     						=  tok(__magic_name__   )['''input_ids''']
													UpperCAmelCase_			:      Optional[int]     						=  tok(__magic_name__   )['''input_ids''']

													assert encoded[-1] == encoded_dot[0]





