






"""simple docstring"""
class 						a_ :







      '''simple docstring'''

      def __init__(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     dict[int, list[int]]								=		{}
       # indexmap keys are an index and it's values are the number at that index
       lowerCamelCase__	:     dict[int, int]								=		{}




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       if isinstance(lowerCamelCase_,	(range, str)   ):
        lowerCamelCase__	:     Dict								=		list(lowerCamelCase_   )
       elif not isinstance(lowerCamelCase_,	lowerCamelCase_   ):
        raise TypeError(
            'binary_search_delete() only accepts either a list, range or str'   )

       lowerCamelCase__	:     Tuple								=		0
       lowerCamelCase__	:     Optional[int]								=		len(lowerCamelCase_   ) - 1

       while low <= high:
        lowerCamelCase__	:     Optional[int]								=		(low + high) // 2
        if array[mid] == item:
         array.pop(lowerCamelCase_   )
         return array
        elif array[mid] < item:
         lowerCamelCase__	:     List[Any]								=		mid + 1
        else:
         lowerCamelCase__	:     Dict								=		mid - 1
       raise ValueError(
           'Either the item is not in the array or the array was unsorted'   )




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       if isinstance(lowerCamelCase_,	(range, str)   ):
        lowerCamelCase__	:     Union[str, Any]								=		list(lowerCamelCase_   )
       elif not isinstance(lowerCamelCase_,	lowerCamelCase_   ):
        raise TypeError(
            'binary_search_insert() only accepts either a list, range or str'   )

       lowerCamelCase__	:     Optional[Any]								=		0
       lowerCamelCase__	:     List[str]								=		len(lowerCamelCase_   ) - 1

       while low <= high:
        lowerCamelCase__	:     int								=		(low + high) // 2
        if array[mid] == index:
         # If the item already exists in the array,
         # insert it after the existing item
         array.insert(mid + 1,	lowerCamelCase_   )
         return array
        elif array[mid] < index:
         lowerCamelCase__	:     List[Any]								=		mid + 1
        else:
         lowerCamelCase__	:     Union[str, Any]								=		mid - 1

        # If the item doesn't exist in the array, insert it at the appropriate position
       array.insert(lowerCamelCase_,	lowerCamelCase_   )
       return array




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       if index in self.indexmap:
        lowerCamelCase__	:     Union[str, Any]								=		self.indexmap[index]
        if len(self.numbermap[n]   ) == 1:
         del self.numbermap[n]
        else:
         lowerCamelCase__	:     Union[str, Any]								=		self.binary_search_delete(self.numbermap[n],	lowerCamelCase_   )

        # Set new index
       lowerCamelCase__	:     Any								=		number

       # Number not seen before or empty so insert number value
       if number not in self.numbermap:
        lowerCamelCase__	:     Union[str, Any]								=		[index]

       # Here we need to perform a binary search insertion in order to insert
       # The item in the correct place
       else:
        lowerCamelCase__	:     Any								=		self.binary_search_insert(
            self.numbermap[number],	lowerCamelCase_   )





      def      a__				(self,	lowerCamelCase_   ):

       '''simple docstring'''



       return self.numbermap.get(lowerCamelCase_,	[-1]   )[0]


if __name__ == "__main__":
      import doctest

      doctest.testmod()









"""simple docstring"""
import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 						a_ (      snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

      lowerCamelCase__			:							Optional[Any]					=      KandinskyPriorPipeline
      lowerCamelCase__			:							Any					=      ['prompt']
      lowerCamelCase__			:							Any					=      ['prompt', 'negative_prompt']
      lowerCamelCase__			:							str					=      [
          'num_images_per_prompt',
          'generator',
          'num_inference_steps',
          'latents',
          'negative_prompt',
          'guidance_scale',
          'output_type',
          'return_dict',
      ]
      lowerCamelCase__			:							Dict					=      False




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 3_2




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return self.time_input_dim * 4




      @property
      def      a__				(self   ):

       '''simple docstring'''



       return 1_0_0




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )
       return tokenizer




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     int								=		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=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,	)
       return CLIPTextModelWithProjection(lowerCamelCase_   )




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )

       lowerCamelCase__	:     Optional[int]								=		{
           'num_attention_heads': 2,
           'attention_head_dim': 1_2,
           'embedding_dim': self.text_embedder_hidden_size,
           'num_layers': 1,
       }

       lowerCamelCase__	:     Optional[int]								=		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
       lowerCamelCase__	:     Dict								=		nn.Parameter(torch.ones(model.clip_std.shape   )   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       torch.manual_seed(0   )
       lowerCamelCase__	:     List[str]								=		CLIPVisionConfig(
           hidden_size=self.text_embedder_hidden_size,	image_size=2_2_4,	projection_dim=self.text_embedder_hidden_size,	intermediate_size=3_7,	num_attention_heads=4,	num_channels=3,	num_hidden_layers=5,	patch_size=1_4,	)

       lowerCamelCase__	:     int								=		CLIPVisionModelWithProjection(lowerCamelCase_   )
       return model




      @property
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		CLIPImageProcessor(
           crop_size=2_2_4,	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_2_4,	)

       return image_processor




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		self.dummy_prior
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_image_encoder
       lowerCamelCase__	:     Optional[Any]								=		self.dummy_text_encoder
       lowerCamelCase__	:     Union[str, Any]								=		self.dummy_tokenizer
       lowerCamelCase__	:     List[Any]								=		self.dummy_image_processor

       lowerCamelCase__	:     List[Any]								=		UnCLIPScheduler(
           variance_type='fixed_small_log',	prediction_type='sample',	num_train_timesteps=1_0_0_0,	clip_sample=lowerCamelCase_,	clip_sample_range=10.0,	)

       lowerCamelCase__	:     Union[str, Any]								=		{
           'prior': prior,
           'image_encoder': image_encoder,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'scheduler': scheduler,
           'image_processor': image_processor,
       }

       return components




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_=0   ):

       '''simple docstring'''



       if str(lowerCamelCase_   ).startswith('mps'   ):
        lowerCamelCase__	:     List[Any]								=		torch.manual_seed(lowerCamelCase_   )
       else:
        lowerCamelCase__	:     Optional[int]								=		torch.Generator(device=lowerCamelCase_   ).manual_seed(lowerCamelCase_   )
       lowerCamelCase__	:     List[Any]								=		{
           'prompt': 'horse',
           'generator': generator,
           'guidance_scale': 4.0,
           'num_inference_steps': 2,
           'output_type': 'np',
       }
       return inputs




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		'cpu'

       lowerCamelCase__	:     str								=		self.get_dummy_components()

       lowerCamelCase__	:     Any								=		self.pipeline_class(**lowerCamelCase_   )
       lowerCamelCase__	:     Dict								=		pipe.to(lowerCamelCase_   )

       pipe.set_progress_bar_config(disable=lowerCamelCase_   )

       lowerCamelCase__	:     Tuple								=		pipe(**self.get_dummy_inputs(lowerCamelCase_   )   )
       lowerCamelCase__	:     Dict								=		output.image_embeds

       lowerCamelCase__	:     Optional[Any]								=		pipe(
           **self.get_dummy_inputs(lowerCamelCase_   ),	return_dict=lowerCamelCase_,	)[0]

       lowerCamelCase__	:     Dict								=		image[0, -1_0:]
       lowerCamelCase__	:     Tuple								=		image_from_tuple[0, -1_0:]

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

       lowerCamelCase__	:     Dict								=		np.array(
           [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]   )

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

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		torch_device == 'cpu'
       lowerCamelCase__	:     Any								=		True
       lowerCamelCase__	:     List[Any]								=		False

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





      @skip_mps
      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     str								=		torch_device == 'cpu'
       lowerCamelCase__	:     int								=		False

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

