

'''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




'''simple docstring'''






from __future__ import annotations

from random import random
from typing import Generic, TypeVar

lowerCAmelCase__											=	TypeVar('''KT''')
lowerCAmelCase__											=	TypeVar('''VT''')






class 			lowercase_	(Generic[KT, VT]      ):




  """simple docstring"""




  def __init__(      self   :     Optional[Any]					,lowercase__   :     KT | str = "root"					,lowercase__   :     VT | None = None			):
   __lowercase							  = key
   __lowercase							  = value
   __lowercase							  = []






  def __repr__(      self   :     Tuple			):
   return F"Node({self.key}: {self.value})"






  @property
  def 					SCREAMING_SNAKE_CASE      (      self   :     int			):
   return len(self.forward			)






class 			lowercase_	(Generic[KT, VT]      ):




  """simple docstring"""




  def __init__(      self   :     int					,lowercase__   :     float = 0.5					,lowercase__   :     int = 1_6			):
   __lowercase							  = Node[KT, VT]()
   __lowercase							  = 0
   __lowercase							  = p
   __lowercase							  = max_level






  def __str__(      self   :     List[str]			):
   __lowercase							  = list(self			)

   if len(lowercase__			) == 0:
    return F"SkipList(level={self.level})"

   __lowercase							  = max((len(str(lowercase__			)			) for item in items)					,default=4			)
   __lowercase							  = max(lowercase__					,4			) + 4

   __lowercase							  = self.head
   __lowercase							  = []

   __lowercase							  = node.forward.copy()
   lines.append(F"[{node.key}]".ljust(lowercase__					,'''-'''			) + '''* ''' * len(lowercase__			)			)
   lines.append(''' ''' * label_size + '''| ''' * len(lowercase__			)			)

   while len(node.forward			) != 0:
    __lowercase							  = node.forward[0]

    lines.append(
        F"[{node.key}]".ljust(lowercase__					,'''-'''			)
        + ''' '''.join(str(n.key			) if n.key == node.key else '''|''' for n in forwards			)			)
    lines.append(''' ''' * label_size + '''| ''' * len(lowercase__			)			)
    __lowercase							  = node.forward

   lines.append('''None'''.ljust(lowercase__			) + '''* ''' * len(lowercase__			)			)
   return F"SkipList(level={self.level})\n" + "\n".join(lowercase__			)






  def __iter__(      self   :     List[str]			):
   __lowercase							  = self.head

   while len(node.forward			) != 0:
    yield node.forward[0].key
    __lowercase							  = node.forward[0]






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   __lowercase							  = 1
   while random() < self.p and level < self.max_level:
    level += 1

   return level






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]					,lowercase__   :     str			):
   __lowercase							  = []

   __lowercase							  = self.head

   for i in reversed(range(self.level			)			):
    # i < node.level - When node level is lesser than `i` decrement `i`.
    # node.forward[i].key < key - Jumping to node with key value higher
    #                             or equal to searched key would result
    #                             in skipping searched key.
    while i < node.level and node.forward[i].key < key:
     __lowercase							  = node.forward[i]
    # Each leftmost node (relative to searched node) will potentially have to
    # be updated.
    update_vector.append(lowercase__			)

   update_vector.reverse()  # Note that we were inserting values in reverse order.

   # len(node.forward) != 0 - If current node doesn't contain any further
   #                          references then searched key is not present.
   # node.forward[0].key == key - Next node key should be equal to search key
   #                              if key is present.
   if len(node.forward			) != 0 and node.forward[0].key == key:
    return node.forward[0], update_vector
   else:
    return None, update_vector






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]					,lowercase__   :     KT			):
   __lowercase  ,	__lowercase							  = self._locate_node(lowercase__			)

   if node is not None:
    for i, update_node in enumerate(lowercase__			):
     # Remove or replace all references to removed node.
     if update_node.level > i and update_node.forward[i].key == key:
      if node.level > i:
       __lowercase							  = node.forward[i]
      else:
       __lowercase							  = update_node.forward[:i]






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]					,lowercase__   :     KT					,lowercase__   :     VT			):
   __lowercase  ,	__lowercase							  = self._locate_node(lowercase__			)
   if node is not None:
    __lowercase							  = value
   else:
    __lowercase							  = self.random_level()

    if level > self.level:
     # After level increase we have to add additional nodes to head.
     for _ in range(self.level - 1					,lowercase__			):
      update_vector.append(self.head			)
     __lowercase							  = level

    __lowercase							  = Node(lowercase__					,lowercase__			)

    for i, update_node in enumerate(update_vector[:level]			):
     # Change references to pass through new node.
     if update_node.level > i:
      new_node.forward.append(update_node.forward[i]			)

     if update_node.level < i + 1:
      update_node.forward.append(lowercase__			)
     else:
      __lowercase							  = new_node






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]					,lowercase__   :     VT			):
   __lowercase  ,	__lowercase							  = self._locate_node(lowercase__			)

   if node is not None:
    return node.value

   return None


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()
 skip_list.insert('''Key1'''     ,				3      )
 skip_list.insert('''Key2'''     ,				12      )
 skip_list.insert('''Key3'''     ,				41      )
 skip_list.insert('''Key4'''     ,				-19      )

 __lowercase							  = skip_list.head
 __lowercase							  = {}
 while node.level != 0:
  __lowercase							  = node.forward[0]
  __lowercase							  = node.value

 assert len(A__      ) == 4
 assert all_values["Key1"] == 3
 assert all_values["Key2"] == 12
 assert all_values["Key3"] == 41
 assert all_values["Key4"] == -19


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()
 skip_list.insert('''Key1'''     ,				10      )
 skip_list.insert('''Key1'''     ,				12      )

 skip_list.insert('''Key5'''     ,				7      )
 skip_list.insert('''Key7'''     ,				10      )
 skip_list.insert('''Key10'''     ,				5      )

 skip_list.insert('''Key7'''     ,				7      )
 skip_list.insert('''Key5'''     ,				5      )
 skip_list.insert('''Key10'''     ,				10      )

 __lowercase							  = skip_list.head
 __lowercase							  = {}
 while node.level != 0:
  __lowercase							  = node.forward[0]
  __lowercase							  = node.value

 if len(A__      ) != 4:
  print()
 assert len(A__      ) == 4
 assert all_values["Key1"] == 12
 assert all_values["Key7"] == 7
 assert all_values["Key5"] == 5
 assert all_values["Key10"] == 10


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()
 assert skip_list.find('''Some key'''      ) is None


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()

 skip_list.insert('''Key2'''     ,				20      )
 assert skip_list.find('''Key2'''      ) == 20

 skip_list.insert('''Some Key'''     ,				10      )
 skip_list.insert('''Key2'''     ,				8      )
 skip_list.insert('''V'''     ,				13      )

 assert skip_list.find('''Y'''      ) is None
 assert skip_list.find('''Key2'''      ) == 8
 assert skip_list.find('''Some Key'''      ) == 10
 assert skip_list.find('''V'''      ) == 13


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()
 skip_list.delete('''Some key'''      )

 assert len(skip_list.head.forward      ) == 0


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()

 skip_list.insert('''Key1'''     ,				12      )
 skip_list.insert('''V'''     ,				13      )
 skip_list.insert('''X'''     ,				14      )
 skip_list.insert('''Key2'''     ,				15      )

 skip_list.delete('''V'''      )
 skip_list.delete('''Key2'''      )

 assert skip_list.find('''V'''      ) is None
 assert skip_list.find('''Key2'''      ) is None


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()

 skip_list.insert('''Key1'''     ,				12      )
 skip_list.insert('''V'''     ,				13      )
 skip_list.insert('''X'''     ,				14      )
 skip_list.insert('''Key2'''     ,				15      )

 skip_list.delete('''V'''      )
 assert skip_list.find('''V'''      ) is None
 assert skip_list.find('''X'''      ) == 14
 assert skip_list.find('''Key1'''      ) == 12
 assert skip_list.find('''Key2'''      ) == 15

 skip_list.delete('''X'''      )
 assert skip_list.find('''V'''      ) is None
 assert skip_list.find('''X'''      ) is None
 assert skip_list.find('''Key1'''      ) == 12
 assert skip_list.find('''Key2'''      ) == 15

 skip_list.delete('''Key1'''      )
 assert skip_list.find('''V'''      ) is None
 assert skip_list.find('''X'''      ) is None
 assert skip_list.find('''Key1'''      ) is None
 assert skip_list.find('''Key2'''      ) == 15

 skip_list.delete('''Key2'''      )
 assert skip_list.find('''V'''      ) is None
 assert skip_list.find('''X'''      ) is None
 assert skip_list.find('''Key1'''      ) is None
 assert skip_list.find('''Key2'''      ) is None


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()

 skip_list.insert('''Key1'''     ,				12      )
 skip_list.insert('''V'''     ,				13      )
 skip_list.insert('''X'''     ,				142      )
 skip_list.insert('''Key2'''     ,				15      )

 skip_list.delete('''X'''      )

 def traverse_keys(A__      ):
  yield node.key
  for forward_node in node.forward:
   yield from traverse_keys(A__      )

 assert len(set(traverse_keys(skip_list.head      )      )      ) == 4


def 		_A     (    ):






 """simple docstring"""



 def is_sorted(A__      ):
  return all(next_item >= item for item, next_item in zip(A__     ,				lst[1:]      )      )

 __lowercase							  = SkipList()
 for i in range(10      ):
  skip_list.insert(A__     ,				A__      )
 assert is_sorted(list(A__      )      )
 skip_list.delete(5      )
 skip_list.delete(8      )
 skip_list.delete(2      )
 assert is_sorted(list(A__      )      )
 skip_list.insert(-12     ,				-12      )
 skip_list.insert(77     ,				77      )
 assert is_sorted(list(A__      )      )


def 		_A     (    ):






 """simple docstring"""



 for _ in range(100      ):
  # Repeat test 100 times due to the probabilistic nature of skip list
  # random values == random bugs
  test_insert()
  test_insert_overrides_existing_value()

  test_searching_empty_list_returns_none()
  test_search()

  test_deleting_item_from_empty_list_do_nothing()
  test_deleted_items_are_not_founded_by_find_method()
  test_delete_removes_only_given_key()
  test_delete_doesnt_leave_dead_nodes()

  test_iter_always_yields_sorted_values()


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = SkipList()
 skip_list.insert(2     ,				'''2'''      )
 skip_list.insert(4     ,				'''4'''      )
 skip_list.insert(6     ,				'''4'''      )
 skip_list.insert(4     ,				'''5'''      )
 skip_list.insert(8     ,				'''4'''      )
 skip_list.insert(9     ,				'''4'''      )

 skip_list.delete(4      )

 print(A__      )


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 main()

