


"""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 KandinskyVaaPriorPipeline, 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  UpperCamelCase_	( UpperCamelCase			,  unittest.TestCase):

	"""simple docstring"""





	snake_case__				:  int    					=			KandinskyVaaPriorPipeline
	snake_case__				:  List[Any]    					=			["prompt"]
	snake_case__				:  Tuple    					=			["prompt", "negative_prompt"]
	snake_case__				:  Optional[Any]    					=			[
	    "num_images_per_prompt",
	    "generator",
	    "num_inference_steps",
	    "latents",
	    "negative_prompt",
	    "guidance_scale",
	    "output_type",
	    "return_dict",
	]
	snake_case__				:  List[Any]    					=			False




	@property
	def   UpperCAmelCase_      ( self			:				List[str]   )       ->	str:
						return 3_2




	@property
	def   UpperCAmelCase_      ( self			:				Dict   )       ->	Optional[Any]:
						return 3_2




	@property
	def   UpperCAmelCase_      ( self			:				Tuple   )       ->	Union[str, Any]:
						return self.time_input_dim




	@property
	def   UpperCAmelCase_      ( self			:				List[Any]   )       ->	int:
						return self.time_input_dim * 4




	@property
	def   UpperCAmelCase_      ( self			:				List[Any]   )       ->	Dict:
						return 1_0_0




	@property
	def   UpperCAmelCase_      ( self			:				int   )       ->	Union[str, Any]:
						__SCREAMING_SNAKE_CASE						   =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"   )
						return tokenizer




	@property
	def   UpperCAmelCase_      ( self			:				Optional[int]   )       ->	List[Any]:
						torch.manual_seed(0   )
						__SCREAMING_SNAKE_CASE						   =				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(UpperCAmelCase__   )




	@property
	def   UpperCAmelCase_      ( self			:				int   )       ->	str:
						torch.manual_seed(0   )

						__SCREAMING_SNAKE_CASE						   =				{
						    "num_attention_heads": 2,
						    "attention_head_dim": 1_2,
						    "embedding_dim": self.text_embedder_hidden_size,
						    "num_layers": 1,
						}

						__SCREAMING_SNAKE_CASE						   =				PriorTransformer(**UpperCAmelCase__   )
						# 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
						__SCREAMING_SNAKE_CASE						   =				nn.Parameter(torch.ones(model.clip_std.shape   )   )
						return model




	@property
	def   UpperCAmelCase_      ( self			:				List[Any]   )       ->	Union[str, Any]:
						torch.manual_seed(0   )
						__SCREAMING_SNAKE_CASE						   =				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			,			)

						__SCREAMING_SNAKE_CASE						   =				CLIPVisionModelWithProjection(UpperCAmelCase__   )
						return model




	@property
	def   UpperCAmelCase_      ( self			:				Union[str, Any]   )       ->	Optional[int]:
						__SCREAMING_SNAKE_CASE						   =				CLIPImageProcessor(
						    crop_size=2_2_4			,			do_center_crop=UpperCAmelCase__			,			do_normalize=UpperCAmelCase__			,			do_resize=UpperCAmelCase__			,			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   UpperCAmelCase_      ( self			:				Optional[int]   )       ->	Optional[int]:
						__SCREAMING_SNAKE_CASE						   =				self.dummy_prior
						__SCREAMING_SNAKE_CASE						   =				self.dummy_image_encoder
						__SCREAMING_SNAKE_CASE						   =				self.dummy_text_encoder
						__SCREAMING_SNAKE_CASE						   =				self.dummy_tokenizer
						__SCREAMING_SNAKE_CASE						   =				self.dummy_image_processor

						__SCREAMING_SNAKE_CASE						   =				UnCLIPScheduler(
						    variance_type="fixed_small_log"			,			prediction_type="sample"			,			num_train_timesteps=1_0_0_0			,			clip_sample=UpperCAmelCase__			,			clip_sample_range=10.0			,			)

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

						return components




	def   UpperCAmelCase_      ( self			:				int			,			UpperCAmelCase__			:				Tuple			,			UpperCAmelCase__			:				Tuple=0   )       ->	int:
						if str(UpperCAmelCase__   ).startswith("mps"   ):
											__SCREAMING_SNAKE_CASE						   =				torch.manual_seed(UpperCAmelCase__   )
						else:
											__SCREAMING_SNAKE_CASE						   =				torch.Generator(device=UpperCAmelCase__   ).manual_seed(UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				{
						    "prompt": "horse",
						    "generator": generator,
						    "guidance_scale": 4.0,
						    "num_inference_steps": 2,
						    "output_type": "np",
						}
						return inputs




	def   UpperCAmelCase_      ( self			:				Tuple   )       ->	List[str]:
						__SCREAMING_SNAKE_CASE						   =				"cpu"

						__SCREAMING_SNAKE_CASE						   =				self.get_dummy_components()

						__SCREAMING_SNAKE_CASE						   =				self.pipeline_class(**UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				pipe.to(UpperCAmelCase__   )

						pipe.set_progress_bar_config(disable=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				pipe(**self.get_dummy_inputs(UpperCAmelCase__   )   )
						__SCREAMING_SNAKE_CASE						   =				output.image_embeds

						__SCREAMING_SNAKE_CASE						   =				pipe(
						    **self.get_dummy_inputs(UpperCAmelCase__   )			,			return_dict=UpperCAmelCase__			,			)[0]

						__SCREAMING_SNAKE_CASE						   =				image[0, -1_0:]
						__SCREAMING_SNAKE_CASE						   =				image_from_tuple[0, -1_0:]

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

						__SCREAMING_SNAKE_CASE						   =				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   UpperCAmelCase_      ( self			:				Any   )       ->	str:
						__SCREAMING_SNAKE_CASE						   =				torch_device == "cpu"
						__SCREAMING_SNAKE_CASE						   =				True
						__SCREAMING_SNAKE_CASE						   =				False

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




	@skip_mps
	def   UpperCAmelCase_      ( self			:				List[str]   )       ->	Dict:
						__SCREAMING_SNAKE_CASE						   =				torch_device == "cpu"
						__SCREAMING_SNAKE_CASE						   =				False

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




"""simple docstring"""







import pytest

from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs




@pytest.mark.parametrize(
    "kwargs, expected"  ,						[
        ({"num_shards": 0, "max_num_jobs": 1}, []),
        ({"num_shards": 10, "max_num_jobs": 1}, [range(10   )]),
        ({"num_shards": 10, "max_num_jobs": 10}, [range(lowerCAmelCase_  ,						i + 1   ) for i in range(10   )]),
        ({"num_shards": 1, "max_num_jobs": 10}, [range(1   )]),
        ({"num_shards": 10, "max_num_jobs": 3}, [range(0  ,						4   ), range(4  ,						7   ), range(7  ,						10   )]),
        ({"num_shards": 3, "max_num_jobs": 10}, [range(0  ,						1   ), range(1  ,						2   ), range(2  ,						3   )]),
    ]  ,						)
def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						   =				_distribute_shards(**lowerCAmelCase_   )
					assert out == expected




@pytest.mark.parametrize(
    "gen_kwargs, max_num_jobs, expected"  ,						[
        ({"foo": 0}, 10, [{"foo": 0}]),
        ({"shards": [0, 1, 2, 3]}, 1, [{"shards": [0, 1, 2, 3]}]),
        ({"shards": [0, 1, 2, 3]}, 4, [{"shards": [0]}, {"shards": [1]}, {"shards": [2]}, {"shards": [3]}]),
        ({"shards": [0, 1]}, 4, [{"shards": [0]}, {"shards": [1]}]),
        ({"shards": [0, 1, 2, 3]}, 2, [{"shards": [0, 1]}, {"shards": [2, 3]}]),
    ]  ,						)
def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						   =				_split_gen_kwargs(lowerCAmelCase_  ,						lowerCAmelCase_   )
					assert out == expected




@pytest.mark.parametrize(
    "gen_kwargs, expected"  ,						[
        ({"foo": 0}, 1),
        ({"shards": [0]}, 1),
        ({"shards": [0, 1, 2, 3]}, 4),
        ({"shards": [0, 1, 2, 3], "foo": 0}, 4),
        ({"shards": [0, 1, 2, 3], "other": (0, 1)}, 4),
        ({"shards": [0, 1, 2, 3], "shards2": [0, 1]}, RuntimeError),
    ]  ,						)
def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					if expected is RuntimeError:
										with pytest.raises(lowerCAmelCase_   ):
															_number_of_shards_in_gen_kwargs(lowerCAmelCase_   )
					else:
										__SCREAMING_SNAKE_CASE						   =				_number_of_shards_in_gen_kwargs(lowerCAmelCase_   )
										assert out == expected
