




'''simple docstring'''





import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class     a  (     UpperCamelCase__			,     unittest.TestCase    ):

     '''simple docstring'''





     lowerCAmelCase       : int     	=						KandinskyVaaPriorEmbaEmbPipeline
     lowerCAmelCase       : Union[str, Any]     	=						["""prompt""", """image"""]
     lowerCAmelCase       : Any     	=						["""prompt""", """image"""]
     lowerCAmelCase       : Tuple     	=						[
         """num_images_per_prompt""",
         """strength""",
         """generator""",
         """num_inference_steps""",
         """latents""",
         """negative_prompt""",
         """guidance_scale""",
         """output_type""",
         """return_dict""",
     ]
     lowerCAmelCase       : Tuple     	=						False
     @property
     def 						lowerCamelCase_     (			self     :    Tuple       ):
         return 32
     @property
     def 						lowerCamelCase_     (			self     :    List[Any]       ):
         return 32
     @property
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         return self.time_input_dim
     @property
     def 						lowerCamelCase_     (			self     :    Dict       ):
         return self.time_input_dim * 4
     @property
     def 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         return 1_00
     @property
     def 						lowerCamelCase_     (			self     :    Dict       ):
         UpperCAmelCase_											=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )
         return tokenizer
     @property
     def 						lowerCamelCase_     (			self     :    List[Any]       ):
         torch.manual_seed(0       )
         UpperCAmelCase_											=  CLIPTextConfig(
             bos_token_id=0      ,					eos_token_id=2      ,					hidden_size=self.text_embedder_hidden_size      ,					projection_dim=self.text_embedder_hidden_size      ,					intermediate_size=37      ,					layer_norm_eps=1E-05      ,					num_attention_heads=4      ,					num_hidden_layers=5      ,					pad_token_id=1      ,					vocab_size=10_00      ,					)
         return CLIPTextModelWithProjection(lowerCAmelCase__       )
     @property
     def 						lowerCamelCase_     (			self     :    List[Any]       ):
         torch.manual_seed(0       )

         UpperCAmelCase_											=  {
             "num_attention_heads": 2,
             "attention_head_dim": 12,
             "embedding_dim": self.text_embedder_hidden_size,
             "num_layers": 1,
         }

         UpperCAmelCase_											=  PriorTransformer(**lowerCAmelCase__       )
         # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
         UpperCAmelCase_											=  nn.Parameter(torch.ones(model.clip_std.shape       )       )
         return model
     @property
     def 						lowerCamelCase_     (			self     :    Optional[int]       ):
         torch.manual_seed(0       )
         UpperCAmelCase_											=  CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size      ,					image_size=2_24      ,					projection_dim=self.text_embedder_hidden_size      ,					intermediate_size=37      ,					num_attention_heads=4      ,					num_channels=3      ,					num_hidden_layers=5      ,					patch_size=14      ,					)

         UpperCAmelCase_											=  CLIPVisionModelWithProjection(lowerCAmelCase__       )
         return model
     @property
     def 						lowerCamelCase_     (			self     :    Dict       ):
         UpperCAmelCase_											=  CLIPImageProcessor(
             crop_size=2_24      ,					do_center_crop=lowerCAmelCase__      ,					do_normalize=lowerCAmelCase__      ,					do_resize=lowerCAmelCase__      ,					image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]      ,					image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]      ,					resample=3      ,					size=2_24      ,					)

         return image_processor
     def 						lowerCamelCase_     (			self     :    Union[str, Any]       ):
         UpperCAmelCase_											=  self.dummy_prior
         UpperCAmelCase_											=  self.dummy_image_encoder
         UpperCAmelCase_											=  self.dummy_text_encoder
         UpperCAmelCase_											=  self.dummy_tokenizer
         UpperCAmelCase_											=  self.dummy_image_processor

         UpperCAmelCase_											=  UnCLIPScheduler(
             variance_type='''fixed_small_log'''      ,					prediction_type='''sample'''      ,					num_train_timesteps=10_00      ,					clip_sample=lowerCAmelCase__      ,					clip_sample_range=10.0      ,					)

         UpperCAmelCase_											=  {
             "prior": prior,
             "image_encoder": image_encoder,
             "text_encoder": text_encoder,
             "tokenizer": tokenizer,
             "scheduler": scheduler,
             "image_processor": image_processor,
         }

         return components
     def 						lowerCamelCase_     (			self     :    Union[str, Any]      ,					__snake_case     :    Tuple      ,					__snake_case     :    Union[str, Any]=0       ):




         if str(lowerCAmelCase__       ).startswith('''mps'''       ):
             UpperCAmelCase_											=  torch.manual_seed(lowerCAmelCase__       )
         else:
             UpperCAmelCase_											=  torch.Generator(device=lowerCAmelCase__       ).manual_seed(lowerCAmelCase__       )

         UpperCAmelCase_											=  floats_tensor((1, 3, 64, 64)      ,					rng=random.Random(lowerCAmelCase__       )       ).to(lowerCAmelCase__       )
         UpperCAmelCase_											=  image.cpu().permute(0      ,					2      ,					3      ,					1       )[0]
         UpperCAmelCase_											=  Image.fromarray(np.uinta(lowerCAmelCase__       )       ).convert('''RGB'''       ).resize((2_56, 2_56)       )

         UpperCAmelCase_											=  {
             "prompt": "horse",
             "image": init_image,
             "strength": 0.5,
             "generator": generator,
             "guidance_scale": 4.0,
             "num_inference_steps": 2,
             "output_type": "np",
         }
         return inputs
     def 						lowerCamelCase_     (			self     :    Optional[Any]       ):
         UpperCAmelCase_											=  "cpu"

         UpperCAmelCase_											=  self.get_dummy_components()

         UpperCAmelCase_											=  self.pipeline_class(**lowerCAmelCase__       )
         UpperCAmelCase_											=  pipe.to(lowerCAmelCase__       )

         pipe.set_progress_bar_config(disable=lowerCAmelCase__       )

         UpperCAmelCase_											=  pipe(**self.get_dummy_inputs(lowerCAmelCase__       )       )
         UpperCAmelCase_											=  output.image_embeds

         UpperCAmelCase_											=  pipe(
             **self.get_dummy_inputs(lowerCAmelCase__       )      ,					return_dict=lowerCAmelCase__      ,					)[0]

         UpperCAmelCase_											=  image[0, -10:]
         UpperCAmelCase_											=  image_from_tuple[0, -10:]

         assert image.shape == (1, 32)

         UpperCAmelCase_											=  np.array(
             [
                 0.1_071_284,
                 1.3_330_271,
                 0.61_260_223,
                 -0.6_691_065,
                 -0.3_846_852,
                 -1.0_303_661,
                 0.22_716_111,
                 0.03_348_901,
                 0.30_040_675,
                 -0.24_805_029,
             ]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < 1E-2
     @skip_mps
     def 						lowerCamelCase_     (			self     :    List[Any]       ):
         UpperCAmelCase_											=  torch_device == "cpu"
         UpperCAmelCase_											=  True
         UpperCAmelCase_											=  False

         self._test_inference_batch_single_identical(
             test_max_difference=lowerCAmelCase__      ,					relax_max_difference=lowerCAmelCase__      ,					test_mean_pixel_difference=lowerCAmelCase__      ,					)




     @skip_mps
     def 						lowerCamelCase_     (			self     :    Union[str, Any]       ):
         UpperCAmelCase_											=  torch_device == "cpu"
         UpperCAmelCase_											=  False

         self._test_attention_slicing_forward_pass(
             test_max_difference=lowerCAmelCase__      ,					test_mean_pixel_difference=lowerCAmelCase__      ,					)











def       SCREAMING_SNAKE_CASE			( )						->							List[Any]:
    UpperCAmelCase_											=  1

    while True:
        if (
            sorted(str(__UpperCamelCase   )   )
            == sorted(str(2 * i   )   )
            == sorted(str(3 * i   )   )
            == sorted(str(4 * i   )   )
            == sorted(str(5 * i   )   )
            == sorted(str(6 * i   )   )
        ):
            return i

        i += 1


if __name__ == "__main__":
 print(solution())





