



"""simple docstring"""


import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
					    MODEL_MAPPING,
					    LevitForImageClassification,
					    LevitForImageClassificationWithTeacher,
					    LevitModel,
					)
					from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import LevitImageProcessor
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def  lowercase__						(		self     :    int   )->List[Any]:
							_UpperCAmelCase					=    self.config_class(**self.inputs_dict   )
							self.parent.assertTrue(hasattr(__UpperCamelCase				,   '''hidden_sizes'''   )   )
							self.parent.assertTrue(hasattr(__UpperCamelCase				,   '''num_attention_heads'''   )   )



class 			_a :
			"""simple docstring"""



			def __init__(		self     :    Any				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    Optional[int]=1_3				,   __UpperCamelCase     :    int=6_4				,   __UpperCamelCase     :    Optional[int]=3				,   __UpperCamelCase     :    List[Any]=3				,   __UpperCamelCase     :    str=2				,   __UpperCamelCase     :    Any=1				,   __UpperCamelCase     :    str=1_6				,   __UpperCamelCase     :    List[Any]=[1_2_8, 2_5_6, 3_8_4]				,   __UpperCamelCase     :    Optional[int]=[4, 6, 8]				,   __UpperCamelCase     :    Any=[2, 3, 4]				,   __UpperCamelCase     :    Any=[1_6, 1_6, 1_6]				,   __UpperCamelCase     :    Any=0				,   __UpperCamelCase     :    Dict=[2, 2, 2]				,   __UpperCamelCase     :    Optional[int]=[2, 2, 2]				,   __UpperCamelCase     :    str=0.0_2				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    List[Any]=True				,   __UpperCamelCase     :    Optional[int]=2				,   )->Optional[int]:
							_UpperCAmelCase					=    parent
							_UpperCAmelCase					=    batch_size
							_UpperCAmelCase					=    image_size
							_UpperCAmelCase					=    num_channels
							_UpperCAmelCase					=    kernel_size
							_UpperCAmelCase					=    stride
							_UpperCAmelCase					=    padding
							_UpperCAmelCase					=    hidden_sizes
							_UpperCAmelCase					=    num_attention_heads
							_UpperCAmelCase					=    depths
							_UpperCAmelCase					=    key_dim
							_UpperCAmelCase					=    drop_path_rate
							_UpperCAmelCase					=    patch_size
							_UpperCAmelCase					=    attention_ratio
							_UpperCAmelCase					=    mlp_ratio
							_UpperCAmelCase					=    initializer_range
							_UpperCAmelCase					=    [
							    ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
							    ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
							]
							_UpperCAmelCase					=    is_training
							_UpperCAmelCase					=    use_labels
							_UpperCAmelCase					=    num_labels
							_UpperCAmelCase					=    initializer_range



			def  lowercase__						(		self     :    int   )->Optional[int]:
							_UpperCAmelCase					=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							_UpperCAmelCase					=    None
							if self.use_labels:
											_UpperCAmelCase					=    ids_tensor([self.batch_size]				,   self.num_labels   )

							_UpperCAmelCase					=    self.get_config()
							return config, pixel_values, labels



			def  lowercase__						(		self     :    Tuple   )->Tuple:
							return LevitConfig(
							    image_size=self.image_size				,   num_channels=self.num_channels				,   kernel_size=self.kernel_size				,   stride=self.stride				,   padding=self.padding				,   patch_size=self.patch_size				,   hidden_sizes=self.hidden_sizes				,   num_attention_heads=self.num_attention_heads				,   depths=self.depths				,   key_dim=self.key_dim				,   drop_path_rate=self.drop_path_rate				,   mlp_ratio=self.mlp_ratio				,   attention_ratio=self.attention_ratio				,   initializer_range=self.initializer_range				,   down_ops=self.down_ops				,   )



			def  lowercase__						(		self     :    Optional[int]				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    List[str]   )->List[Any]:
							_UpperCAmelCase					=    LevitModel(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase   )
							_UpperCAmelCase					=    (self.image_size, self.image_size)
							_UpperCAmelCase		,						_UpperCAmelCase					=    image_size[0], image_size[1]
							for _ in range(4   ):
											_UpperCAmelCase					=    floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1   )
											_UpperCAmelCase					=    floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1   )
							self.parent.assertEqual(
							    result.last_hidden_state.shape				,   (self.batch_size, ceil(height / 4   ) * ceil(width / 4   ), self.hidden_sizes[-1])				,   )



			def  lowercase__						(		self     :    Optional[Any]				,   __UpperCamelCase     :    Optional[Any]				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    List[Any]   )->Union[str, Any]:
							_UpperCAmelCase					=    self.num_labels
							_UpperCAmelCase					=    LevitForImageClassification(__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase				,   labels=__UpperCamelCase   )
							self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)   )



			def  lowercase__						(		self     :    List[str]   )->int:
							_UpperCAmelCase					=    self.prepare_config_and_inputs()
							_UpperCAmelCase		,						_UpperCAmelCase		,						_UpperCAmelCase					=    config_and_inputs
							_UpperCAmelCase					=    {'''pixel_values''': pixel_values}
							return config, inputs_dict



@require_torch
class 			_a (					lowerCAmelCase			,							lowerCAmelCase			,							unittest.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	(
			    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase__			      =	(
			    {
			        'feature-extraction': LevitModel,
			        'image-classification': (LevitForImageClassification, LevitForImageClassificationWithTeacher),
			    }
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False



			def  lowercase__						(		self     :    Optional[int]   )->List[Any]:
							_UpperCAmelCase					=    LevitModelTester(self   )
							_UpperCAmelCase					=    ConfigTester(self				,   config_class=__UpperCamelCase				,   has_text_modality=__UpperCamelCase				,   hidden_size=3_7   )



			def  lowercase__						(		self     :    Tuple   )->Dict:
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()



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



			@unittest.skip(reason='''Levit does not use inputs_embeds'''   )
			def  lowercase__						(		self     :    Union[str, Any]   )->Optional[Any]:
							pass



			@unittest.skip(reason='''Levit does not support input and output embeddings'''   )
			def  lowercase__						(		self     :    Union[str, Any]   )->str:
							pass



			@unittest.skip(reason='''Levit does not output attentions'''   )
			def  lowercase__						(		self     :    List[Any]   )->int:
							pass



			def  lowercase__						(		self     :    int   )->Optional[Any]:
							_UpperCAmelCase		,						_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											_UpperCAmelCase					=    model_class(__UpperCamelCase   )
											_UpperCAmelCase					=    inspect.signature(model.forward   )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											_UpperCAmelCase					=    [*signature.parameters.keys()]

											_UpperCAmelCase					=    ['''pixel_values''']
											self.assertListEqual(arg_names[:1]				,   __UpperCamelCase   )



			def  lowercase__						(		self     :    Any   )->str:







							def check_hidden_states_output(__UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Optional[int]   ):
											_UpperCAmelCase					=    model_class(__UpperCamelCase   )
											model.to(__UpperCamelCase   )
											model.eval()

											with torch.no_grad():
															_UpperCAmelCase					=    model(**self._prepare_for_class(__UpperCamelCase				,   __UpperCamelCase   )   )

											_UpperCAmelCase					=    outputs.hidden_states

											_UpperCAmelCase					=    len(self.model_tester.depths   ) + 1
											self.assertEqual(len(__UpperCamelCase   )				,   __UpperCamelCase   )

											_UpperCAmelCase					=    (self.model_tester.image_size, self.model_tester.image_size)
											_UpperCAmelCase		,						_UpperCAmelCase					=    image_size[0], image_size[1]
											for _ in range(4   ):
															_UpperCAmelCase					=    floor(
															    (
															        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
															        / self.model_tester.stride
															    )
															    + 1   )
															_UpperCAmelCase					=    floor(
															    (
															        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
															        / self.model_tester.stride
															    )
															    + 1   )
											# verify the first hidden states (first block)
											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]   )				,   [
											        height * width,
											        self.model_tester.hidden_sizes[0],
											    ]				,   )

							_UpperCAmelCase		,						_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											_UpperCAmelCase					=    True
											check_hidden_states_output(__UpperCamelCase				,   __UpperCamelCase				,   __UpperCamelCase   )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											_UpperCAmelCase					=    True

											check_hidden_states_output(__UpperCamelCase				,   __UpperCamelCase				,   __UpperCamelCase   )



			@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
			def  lowercase__						(		self     :    int   )->Optional[int]:
							pass



			def  lowercase__						(		self     :    Optional[Any]				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    List[str]=False   )->List[str]:
							_UpperCAmelCase					=    super()._prepare_for_class(__UpperCamelCase				,   __UpperCamelCase				,   return_labels=__UpperCamelCase   )

							if return_labels:
											if model_class.__name__ == "LevitForImageClassificationWithTeacher":
															del inputs_dict["labels"]

							return inputs_dict



			def  lowercase__						(		self     :    Union[str, Any]   )->Tuple:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCamelCase   )



			def  lowercase__						(		self     :    Dict   )->List[Any]:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase   )



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







							if not self.model_tester.is_training:
											return

							_UpperCAmelCase		,						_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCAmelCase					=    True

							for model_class in self.all_model_classes:
											# LevitForImageClassificationWithTeacher supports inference-only
											if (
											    model_class in get_values(__UpperCamelCase   )
											    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
											):
															continue
											_UpperCAmelCase					=    model_class(__UpperCamelCase   )
											model.to(__UpperCamelCase   )
											model.train()
											_UpperCAmelCase					=    self._prepare_for_class(__UpperCamelCase				,   __UpperCamelCase				,   return_labels=__UpperCamelCase   )
											_UpperCAmelCase					=    model(**__UpperCamelCase   ).loss
											loss.backward()



			def  lowercase__						(		self     :    Optional[Any]   )->Any:
							_UpperCAmelCase		,						_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs_for_common()
							if not self.model_tester.is_training:
											return

							_UpperCAmelCase					=    False
							_UpperCAmelCase					=    True

							for model_class in self.all_model_classes:
											if model_class in get_values(__UpperCamelCase   ) or not model_class.supports_gradient_checkpointing:
															continue
											# LevitForImageClassificationWithTeacher supports inference-only
											if model_class.__name__ == "LevitForImageClassificationWithTeacher":
															continue
											_UpperCAmelCase					=    model_class(__UpperCamelCase   )
											model.gradient_checkpointing_enable()
											model.to(__UpperCamelCase   )
											model.train()
											_UpperCAmelCase					=    self._prepare_for_class(__UpperCamelCase				,   __UpperCamelCase				,   return_labels=__UpperCamelCase   )
											_UpperCAmelCase					=    model(**__UpperCamelCase   ).loss
											loss.backward()



			def  lowercase__						(		self     :    List[str]   )->Dict:
							_UpperCAmelCase		,						_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCAmelCase					=    [
							    {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float},
							    {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long},
							    {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float},
							]

							for model_class in self.all_model_classes:
											if (
											    model_class
											    not in [
											        *get_values(__UpperCamelCase   ),
											    ]
											    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
											):
															continue

											for problem_type in problem_types:
															with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'   ):
																			_UpperCAmelCase					=    problem_type['''title''']
																			_UpperCAmelCase					=    problem_type['''num_labels''']

																			_UpperCAmelCase					=    model_class(__UpperCamelCase   )
																			model.to(__UpperCamelCase   )
																			model.train()

																			_UpperCAmelCase					=    self._prepare_for_class(__UpperCamelCase				,   __UpperCamelCase				,   return_labels=__UpperCamelCase   )

																			if problem_type["num_labels"] > 1:
																							_UpperCAmelCase					=    inputs['''labels'''].unsqueeze(1   ).repeat(1				,   problem_type['''num_labels''']   )

																			_UpperCAmelCase					=    inputs['''labels'''].to(problem_type['''dtype''']   )

																			# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																			# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																			# they have the same size." which is a symptom something in wrong for the regression problem.
																			# See https://github.com/huggingface/transformers/issues/11780
																			with warnings.catch_warnings(record=__UpperCamelCase   ) as warning_list:
																							_UpperCAmelCase					=    model(**__UpperCamelCase   ).loss
																			for w in warning_list:
																							if "Using a target size that is different to the input size" in str(w.message   ):
																											raise ValueError(
																											    F'Something is going wrong in the regression problem: intercepted {w.message}'   )

																			loss.backward()



			@slow
			def  lowercase__						(		self     :    Any   )->Optional[int]:







							for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_UpperCAmelCase					=    LevitModel.from_pretrained(__UpperCamelCase   )
											self.assertIsNotNone(__UpperCamelCase   )







def  lowercase	(      ):






				'''simple docstring'''



				_UpperCAmelCase					=    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
				return image
@require_torch
@require_vision
class 			_a (					unittest.TestCase):
			"""simple docstring"""



			@cached_property
			def  lowercase__						(		self     :    Optional[Any]   )->Any:
							return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )



			@slow
			def  lowercase__						(		self     :    List[str]   )->str:
							_UpperCAmelCase					=    LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(
							    __UpperCamelCase   )

							_UpperCAmelCase					=    self.default_image_processor
							_UpperCAmelCase					=    prepare_img()
							_UpperCAmelCase					=    image_processor(images=__UpperCamelCase				,   return_tensors='''pt'''   ).to(__UpperCamelCase   )

							# forward pass
							with torch.no_grad():
											_UpperCAmelCase					=    model(**__UpperCamelCase   )

							# verify the logits
							_UpperCAmelCase					=    torch.Size((1, 1_0_0_0)   )
							self.assertEqual(outputs.logits.shape				,   __UpperCamelCase   )

							_UpperCAmelCase					=    torch.tensor([1.0_4_4_8, -0.3_7_4_5, -1.8_3_1_7]   ).to(__UpperCamelCase   )

							self.assertTrue(torch.allclose(outputs.logits[0, :3]				,   __UpperCamelCase				,   atol=1e-4   )   )










"""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):
			"""simple docstring"""
			UpperCamelCase__			      =	StableDiffusionXLImgaImgPipeline
			UpperCamelCase__			      =	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
			UpperCamelCase__			      =	PipelineTesterMixin.required_optional_params - {"""latents"""}
			UpperCamelCase__			      =	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
			UpperCamelCase__			      =	IMAGE_TO_IMAGE_IMAGE_PARAMS
			UpperCamelCase__			      =	IMAGE_TO_IMAGE_IMAGE_PARAMS



			def  lowercase__						(		self     :    Tuple   )->int:
							torch.manual_seed(0   )
							_UpperCAmelCase					=    UNetaDConditionModel(
							    block_out_channels=(3_2, 6_4)				,   layers_per_block=2				,   sample_size=3_2				,   in_channels=4				,   out_channels=4				,   down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')				,   up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')				,   attention_head_dim=(2, 4)				,   use_linear_projection=__UpperCamelCase				,   addition_embed_type='''text_time'''				,   addition_time_embed_dim=8				,   transformer_layers_per_block=(1, 2)				,   projection_class_embeddings_input_dim=8_0				,   cross_attention_dim=6_4				,   )
							_UpperCAmelCase					=    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					=    AutoencoderKL(
							    block_out_channels=[3_2, 6_4]				,   in_channels=3				,   out_channels=3				,   down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']				,   up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']				,   latent_channels=4				,   sample_size=1_2_8				,   )
							torch.manual_seed(0   )
							_UpperCAmelCase					=    CLIPTextConfig(
							    bos_token_id=0				,   eos_token_id=2				,   hidden_size=3_2				,   intermediate_size=3_7				,   layer_norm_eps=1e-05				,   num_attention_heads=4				,   num_hidden_layers=5				,   pad_token_id=1				,   vocab_size=1_0_0_0				,   hidden_act='''gelu'''				,   projection_dim=3_2				,   )
							_UpperCAmelCase					=    CLIPTextModel(__UpperCamelCase   )
							_UpperCAmelCase					=    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				,   local_files_only=__UpperCamelCase   )

							_UpperCAmelCase					=    CLIPTextModelWithProjection(__UpperCamelCase   )
							_UpperCAmelCase					=    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				,   local_files_only=__UpperCamelCase   )

							_UpperCAmelCase					=    {
							    '''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  lowercase__						(		self     :    int				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    int=0   )->Any:
							_UpperCAmelCase					=    floats_tensor((1, 3, 3_2, 3_2)				,   rng=random.Random(__UpperCamelCase   )   ).to(__UpperCamelCase   )
							_UpperCAmelCase					=    image / 2 + 0.5
							if str(__UpperCamelCase   ).startswith('''mps'''   ):
											_UpperCAmelCase					=    torch.manual_seed(__UpperCamelCase   )
							else:
											_UpperCAmelCase					=    torch.Generator(device=__UpperCamelCase   ).manual_seed(__UpperCamelCase   )
							_UpperCAmelCase					=    {
							    '''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  lowercase__						(		self     :    Any   )->int:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    StableDiffusionXLImgaImgPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

							_UpperCAmelCase					=    self.get_dummy_inputs(__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe(**__UpperCamelCase   ).images
							_UpperCAmelCase					=    image[0, -3:, -3:, -1]

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Optional[Any]   )->Optional[int]:
							super().test_attention_slicing_forward_pass(expected_max_diff=3e-3   )



			def  lowercase__						(		self     :    Optional[Any]   )->List[Any]:
							super().test_inference_batch_single_identical(expected_max_diff=3e-3   )



			def  lowercase__						(		self     :    List[str]   )->str:
							pass



			def  lowercase__						(		self     :    Dict   )->List[str]:
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    StableDiffusionXLImgaImgPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

							# forward without prompt embeds
							_UpperCAmelCase					=    self.get_dummy_inputs(__UpperCamelCase   )
							_UpperCAmelCase					=    3 * ['''this is a negative prompt''']
							_UpperCAmelCase					=    negative_prompt
							_UpperCAmelCase					=    3 * [inputs['''prompt''']]

							_UpperCAmelCase					=    sd_pipe(**__UpperCamelCase   )
							_UpperCAmelCase					=    output.images[0, -3:, -3:, -1]

							# forward with prompt embeds
							_UpperCAmelCase					=    self.get_dummy_inputs(__UpperCamelCase   )
							_UpperCAmelCase					=    3 * ['''this is a negative prompt''']
							_UpperCAmelCase					=    3 * [inputs.pop('''prompt'''   )]

							(
							    (
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						
							)					=    sd_pipe.encode_prompt(__UpperCamelCase				,   negative_prompt=__UpperCamelCase   )

							_UpperCAmelCase					=    sd_pipe(
							    **__UpperCamelCase				,   prompt_embeds=__UpperCamelCase				,   negative_prompt_embeds=__UpperCamelCase				,   pooled_prompt_embeds=__UpperCamelCase				,   negative_pooled_prompt_embeds=__UpperCamelCase				,   )
							_UpperCAmelCase					=    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):
			"""simple docstring"""



			def  lowercase__						(		self     :    Union[str, Any]   )->Any:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



			def  lowercase__						(		self     :    Optional[Any]				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    Dict="cpu"				,   __UpperCamelCase     :    int=torch.floataa				,   __UpperCamelCase     :    Optional[Any]=0   )->Union[str, Any]:
							_UpperCAmelCase					=    torch.Generator(device=__UpperCamelCase   ).manual_seed(__UpperCamelCase   )
							_UpperCAmelCase					=    np.random.RandomState(__UpperCamelCase   ).standard_normal((1, 4, 6_4, 6_4)   )
							_UpperCAmelCase					=    torch.from_numpy(__UpperCamelCase   ).to(device=__UpperCamelCase				,   dtype=__UpperCamelCase   )
							_UpperCAmelCase					=    {
							    '''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  lowercase__						(		self     :    Optional[Any]   )->Optional[Any]:
							_UpperCAmelCase					=    DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''   )
							pipe.to(__UpperCamelCase   )
							pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

							assert image.shape == (1, 5_1_2, 5_1_2, 3)
							_UpperCAmelCase					=    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



