

'''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 			lowercase_	(lowerCamelCase__				,       lowerCamelCase__				,       unittest.TestCase      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  str							=			StableDiffusionXLImgaImgPipeline
  SCREAMING_SNAKE_CASE    :  Any							=			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
  SCREAMING_SNAKE_CASE    :  Dict							=			PipelineTesterMixin.required_optional_params - {'latents'}
  SCREAMING_SNAKE_CASE    :  Dict							=			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  SCREAMING_SNAKE_CASE    :  Dict							=			IMAGE_TO_IMAGE_IMAGE_PARAMS
  SCREAMING_SNAKE_CASE    :  Any							=			IMAGE_TO_IMAGE_IMAGE_PARAMS






  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   torch.manual_seed(0			)
   __lowercase							  = 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=lowercase__					,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					,)
   __lowercase							  = 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			)
   __lowercase							  = 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			)
   __lowercase							  = CLIPTextConfig(
       bos_token_id=0					,eos_token_id=2					,hidden_size=3_2					,intermediate_size=3_7					,layer_norm_eps=1e-0_5					,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					,)
   __lowercase							  = CLIPTextModel(lowercase__			)
   __lowercase							  = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''					,local_files_only=lowercase__			)

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

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

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

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

   __lowercase							  = 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 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]			):
   super().test_attention_slicing_forward_pass(expected_max_diff=3e-3			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   super().test_inference_batch_single_identical(expected_max_diff=3e-3			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]			):
   pass






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   __lowercase							  = self.get_dummy_components()
   __lowercase							  = StableDiffusionXLImgaImgPipeline(**lowercase__			)
   __lowercase							  = sd_pipe.to(lowercase__			)
   __lowercase							  = sd_pipe.to(lowercase__			)
   sd_pipe.set_progress_bar_config(disable=lowercase__			)

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

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

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

   (
       (
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	
   )							  = sd_pipe.encode_prompt(lowercase__					,negative_prompt=lowercase__			)

   __lowercase							  = sd_pipe(
       **lowercase__					,prompt_embeds=lowercase__					,negative_prompt_embeds=lowercase__					,pooled_prompt_embeds=lowercase__					,negative_pooled_prompt_embeds=lowercase__					,)
   __lowercase							  = 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 			lowercase_	(unittest.TestCase      ):




  """simple docstring"""




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






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

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

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






from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar

SCREAMING_SNAKE_CASE_:List[Any]             =						TypeVar("""KEY""")
SCREAMING_SNAKE_CASE_:Dict             =						TypeVar("""VAL""")






@dataclass(frozen=SCREAMING_SNAKE_CASE__ ,						slots=SCREAMING_SNAKE_CASE__    )
class SCREAMING_SNAKE_CASE__     (		Generic[KEY, VAL]    ):




    '''simple docstring'''






    __lowerCamelCase			: KEY
    __lowerCamelCase			: VAL






class SCREAMING_SNAKE_CASE__     (		_Item    ):




    '''simple docstring'''






    def __init__(       self		):
        super().__init__(lowerCamelCase__,		lowerCamelCase__		)






    def __bool__(       self		):
        return False


SCREAMING_SNAKE_CASE_:Optional[Any]             =						_DeletedItem()






class SCREAMING_SNAKE_CASE__     (		MutableMapping[KEY, VAL]    ):




    '''simple docstring'''






    def __init__(       self,		lowerCamelCase__ = 8,		lowerCamelCase__ = 0.75		):
        A :       List[str]          =   initial_block_size
        A :       list[_Item | None]          =   [None] * initial_block_size
        assert 0.0 < capacity_factor < 1.0
        A :       Dict          =   capacity_factor
        A :       Optional[Any]          =   0






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        return hash(lowerCamelCase__		) % len(self._buckets		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        return (ind + 1) % len(self._buckets		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        A :       List[Any]          =   self._buckets[ind]
        if not stored:
            A :       Optional[int]          =   _Item(lowerCamelCase__,		lowerCamelCase__		)
            self._len += 1
            return True
        elif stored.key == key:
            A :       int          =   _Item(lowerCamelCase__,		lowerCamelCase__		)
            return True
        else:
            return False






    def 			_lowerCAmelCase					(       self		):
        A :       Union[str, Any]          =   len(self._buckets		) * self._capacity_factor
        return len(self		) >= int(lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self		):
        if len(self._buckets		) <= self._initial_block_size:
            return False
        A :       Optional[Any]          =   len(self._buckets		) * self._capacity_factor / 2
        return len(self		) < limit






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        A :       Dict          =   self._buckets
        A :       Optional[Any]          =   [None] * new_size
        A :       List[str]          =   0
        for item in old_buckets:
            if item:
                self._add_item(item.key,		item.val		)






    def 			_lowerCAmelCase					(       self		):
        self._resize(len(self._buckets		) * 2		)






    def 			_lowerCAmelCase					(       self		):
        self._resize(len(self._buckets		) // 2		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__		):
        A :       Union[str, Any]          =   self._get_bucket_index(lowerCamelCase__		)
        for _ in range(len(self._buckets		)		):
            yield ind
            A :       Dict          =   self._get_next_ind(lowerCamelCase__		)






    def 			_lowerCAmelCase					(       self,		lowerCamelCase__,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            if self._try_set(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
                break






    def __setitem__(       self,		lowerCamelCase__,		lowerCamelCase__		):
        if self._is_full():
            self._size_up()

        self._add_item(lowerCamelCase__,		lowerCamelCase__		)






    def __delitem__(       self,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            A :       Tuple          =   self._buckets[ind]
            if item is None:
                raise KeyError(lowerCamelCase__		)
            if item is _deleted:
                continue
            if item.key == key:
                A :       int          =   _deleted
                self._len -= 1
                break
        if self._is_sparse():
            self._size_down()






    def __getitem__(       self,		lowerCamelCase__		):
        for ind in self._iterate_buckets(lowerCamelCase__		):
            A :       int          =   self._buckets[ind]
            if item is None:
                break
            if item is _deleted:
                continue
            if item.key == key:
                return item.val
        raise KeyError(lowerCamelCase__		)






    def __len__(       self		):
        return self._len






    def __iter__(       self		):
        yield from (item.key for item in self._buckets if item)






    def __repr__(       self		):
        A :       Union[str, Any]          =   """ ,""".join(
            f'''{item.key}: {item.val}''' for item in self._buckets if item		)
        return f'''HashMap({val_string})'''


