




'''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				(			SCREAMING_SNAKE_CASE ):





       '''simple docstring'''






       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						self.config_class(**self.inputs_dict  )
             self.parent.assertTrue(hasattr(A,							'hidden_sizes'  )  )
             self.parent.assertTrue(hasattr(A,							'num_attention_heads'  )  )






class 							_a				:





       '''simple docstring'''






       def __init__(      self,							A,							A=13,							A=64,							A=3,							A=3,							A=2,							A=1,							A=16,							A=[128, 256, 384],							A=[4, 6, 8],							A=[2, 3, 4],							A=[16, 16, 16],							A=0,							A=[2, 2, 2],							A=[2, 2, 2],							A=0.02,							A=True,							A=True,							A=2,							):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						parent
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						batch_size
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						image_size
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						num_channels
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						kernel_size
             SCREAMING_SNAKE_CASE   :      Tuple    					=						stride
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						padding
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						hidden_sizes
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						num_attention_heads
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						depths
             SCREAMING_SNAKE_CASE   :      Tuple    					=						key_dim
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						drop_path_rate
             SCREAMING_SNAKE_CASE   :      Any    					=						patch_size
             SCREAMING_SNAKE_CASE   :      Any    					=						attention_ratio
             SCREAMING_SNAKE_CASE   :      List[str]    					=						mlp_ratio
             SCREAMING_SNAKE_CASE   :      int    					=						initializer_range
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						[
                 ['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],
             ]
             SCREAMING_SNAKE_CASE   :      str    					=						is_training
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						use_labels
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						num_labels
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						initializer_range







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						None
             if self.use_labels:
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						ids_tensor([self.batch_size],							self.num_labels  )

             SCREAMING_SNAKE_CASE   :      str    					=						self.get_config()
             return config, pixel_values, labels







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             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        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						LevitModel(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						model(A  )
             SCREAMING_SNAKE_CASE   :      int    					=						(self.image_size, self.image_size)
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						image_size[0], image_size[1]
             for _ in range(4  ):
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1  )
                   SCREAMING_SNAKE_CASE   :      int    					=						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        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						self.num_labels
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						LevitForImageClassification(A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      Tuple    					=						model(A,							labels=A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.num_labels)  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.prepare_config_and_inputs()
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      str    					=						config_and_inputs
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						{'pixel_values': pixel_values}
             return config, inputs_dict






@require_torch
class 							_a				(			SCREAMING_SNAKE_CASE ,      SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Dict        =						(
           (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
           if is_torch_available()
           else ()
       )
       A						:				Optional[int]        =						(
           {
               '''feature-extraction''': LevitModel,
               '''image-classification''': (LevitForImageClassification, LevitForImageClassificationWithTeacher),
           }
           if is_torch_available()
           else {}
       )

       A						:				Optional[Any]        =						False
       A						:				List[Any]        =						False
       A						:				str        =						False
       A						:				Dict        =						False
       A						:				Dict        =						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						LevitModelTester(self  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						ConfigTester(self,							config_class=A,							has_text_modality=A,							hidden_size=37  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return







       @unittest.skip(reason='Levit does not use inputs_embeds'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='Levit does not support input and output embeddings'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='Levit does not output attentions'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Tuple    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model_class(A  )
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						inspect.signature(model.forward  )
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						[*signature.parameters.keys()]

                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						['pixel_values']
                   self.assertListEqual(arg_names[:1],							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             def check_hidden_states_output(A,							A,							A  ):
                   SCREAMING_SNAKE_CASE   :      Any    					=						model_class(A  )
                   model.to(A  )
                   model.eval()

                   with torch.no_grad():
                         SCREAMING_SNAKE_CASE   :      Tuple    					=						model(**self._prepare_for_class(A,							A  )  )

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						outputs.hidden_states

                   SCREAMING_SNAKE_CASE   :      Dict    					=						len(self.model_tester.depths  ) + 1
                   self.assertEqual(len(A  ),							A  )

                   SCREAMING_SNAKE_CASE   :      List[str]    					=						(self.model_tester.image_size, self.model_tester.image_size)
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Any    					=						image_size[0], image_size[1]
                   for _ in range(4  ):
                         SCREAMING_SNAKE_CASE   :      List[str]    					=						floor(
                             (
                                 (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
                                 / self.model_tester.stride
                             )
                             + 1  )
                         SCREAMING_SNAKE_CASE   :      str    					=						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],
                       ],							)

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True
                   check_hidden_states_output(A,							A,							A  )

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True

                   check_hidden_states_output(A,							A,							A  )







       @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self,							A,							A,							A=False  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						super()._prepare_for_class(A,							A,							return_labels=A  )

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

             return inputs_dict







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.model_tester.prepare_config_and_inputs_for_common()
             SCREAMING_SNAKE_CASE   :      Dict    					=						True

             for model_class in self.all_model_classes:
                   # LevitForImageClassificationWithTeacher supports inference-only
                   if (
                       model_class in get_values(A  )
                       or model_class.__name__ == "LevitForImageClassificationWithTeacher"
                   ):
                         continue
                   SCREAMING_SNAKE_CASE   :      Any    					=						model_class(A  )
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Tuple    					=						self.model_tester.prepare_config_and_inputs_for_common()
             if not self.model_tester.is_training:
                   return

             SCREAMING_SNAKE_CASE   :      Tuple    					=						False
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						True

             for model_class in self.all_model_classes:
                   if model_class in get_values(A  ) or not model_class.supports_gradient_checkpointing:
                         continue
                   # LevitForImageClassificationWithTeacher supports inference-only
                   if model_class.__name__ == "LevitForImageClassificationWithTeacher":
                         continue
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model_class(A  )
                   model.gradient_checkpointing_enable()
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      Any    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[str]    					=						self.model_tester.prepare_config_and_inputs_for_common()

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						[
                 {'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(A  ),
                       ]
                       or model_class.__name__ == "LevitForImageClassificationWithTeacher"
                   ):
                         continue

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

                               SCREAMING_SNAKE_CASE   :      Tuple    					=						model_class(A  )
                               model.to(A  )
                               model.train()

                               SCREAMING_SNAKE_CASE   :      Tuple    					=						self._prepare_for_class(A,							A,							return_labels=A  )

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

                               SCREAMING_SNAKE_CASE   :      Optional[int]    					=						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=A  ) as warning_list:
                                     SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						model(**A  ).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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						LevitModel.from_pretrained(A  )
                   self.assertIsNotNone(A  )




def   lowercase__(			):

      """simple docstring"""






      SCREAMING_SNAKE_CASE   :      Optional[int]    					=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
      return image






@require_torch
@require_vision
class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       @cached_property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  ).to(
                 A  )

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      str    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      int    					=						image_processor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						model(**A  )

             # verify the logits
             SCREAMING_SNAKE_CASE   :      Any    					=						torch.Size((1, 1_000)  )
             self.assertEqual(outputs.logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						torch.tensor([1.04_48, -0.37_45, -1.83_17]  ).to(A  )

             self.assertTrue(torch.allclose(outputs.logits[0, :3],							A,							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				(			SCREAMING_SNAKE_CASE ,      SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Union[str, Any]        =						StableDiffusionXLImgaImgPipeline
       A						:				Any        =						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
       A						:				str        =						PipelineTesterMixin.required_optional_params - {'''latents'''}
       A						:				List[str]        =						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
       A						:				Dict        =						IMAGE_TO_IMAGE_IMAGE_PARAMS
       A						:				int        =						IMAGE_TO_IMAGE_IMAGE_PARAMS







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             torch.manual_seed(0  )
             SCREAMING_SNAKE_CASE   :      Any    					=						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=A,							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,							)
             SCREAMING_SNAKE_CASE   :      str    					=						EulerDiscreteScheduler(
                 beta_start=0.0_00_85,							beta_end=0.0_12,							steps_offset=1,							beta_schedule='scaled_linear',							timestep_spacing='leading',							)
             torch.manual_seed(0  )
             SCREAMING_SNAKE_CASE   :      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=128,							)
             torch.manual_seed(0  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						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,							hidden_act='gelu',							projection_dim=32,							)
             SCREAMING_SNAKE_CASE   :      int    					=						CLIPTextModel(A  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip',							local_files_only=A  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						CLIPTextModelWithProjection(A  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip',							local_files_only=A  )

             SCREAMING_SNAKE_CASE   :      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,							A,							A=0  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						floats_tensor((1, 3, 32, 32),							rng=random.Random(A  )  ).to(A  )
             SCREAMING_SNAKE_CASE   :      str    					=						image / 2 + 0.5
             if str(A  ).startswith('mps'  ):
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.manual_seed(A  )
             else:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.Generator(device=A  ).manual_seed(A  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						{
                 '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.75,
             }
             return inputs







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						'cpu'  # ensure determinism for the device-dependent torch.Generator
             SCREAMING_SNAKE_CASE   :      str    					=						self.get_dummy_components()
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						StableDiffusionXLImgaImgPipeline(**A  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						sd_pipe.to(A  )
             sd_pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.get_dummy_inputs(A  )
             SCREAMING_SNAKE_CASE   :      Any    					=						sd_pipe(**A  ).images
             SCREAMING_SNAKE_CASE   :      Dict    					=						image[0, -3:, -3:, -1]

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

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]  )

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             super().test_attention_slicing_forward_pass(expected_max_diff=3E-3  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             super().test_inference_batch_single_identical(expected_max_diff=3E-3  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.get_dummy_components()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						StableDiffusionXLImgaImgPipeline(**A  )
             SCREAMING_SNAKE_CASE   :      str    					=						sd_pipe.to(A  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						sd_pipe.to(A  )
             sd_pipe.set_progress_bar_config(disable=A  )

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

             SCREAMING_SNAKE_CASE   :      int    					=						sd_pipe(**A  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						output.images[0, -3:, -3:, -1]

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

             (
                 (
                 SCREAMING_SNAKE_CASE
             )					,    (
                 SCREAMING_SNAKE_CASE
             )					,    (
                 SCREAMING_SNAKE_CASE
             )					,    (
                 SCREAMING_SNAKE_CASE
             )					,    
             )   :      Optional[Any]    					=						sd_pipe.encode_prompt(A,							negative_prompt=A  )

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						sd_pipe(
                 **A,							prompt_embeds=A,							negative_prompt_embeds=A,							pooled_prompt_embeds=A,							negative_pooled_prompt_embeds=A,							)
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A,							A="cpu",							A=torch.floataa,							A=0  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						torch.Generator(device=A  ).manual_seed(A  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						np.random.RandomState(A  ).standard_normal((1, 4, 64, 64)  )
             SCREAMING_SNAKE_CASE   :      str    					=						torch.from_numpy(A  ).to(device=A,							dtype=A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						{
                 '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  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'  )
             pipe.to(A  )
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.get_inputs(A  )
             SCREAMING_SNAKE_CASE   :      str    					=						pipe(**A  ).images
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						image[0, -3:, -3:, -1].flatten()

             assert image.shape == (1, 512, 512, 3)
             SCREAMING_SNAKE_CASE   :      Dict    					=						np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]  )
             assert np.abs(image_slice - expected_slice  ).max() < 7E-3


