


'''simple docstring'''






from sklearn.metrics import mean_squared_error

import datasets


__A	:	Optional[int]     =     '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n'

__A	:	Dict     =     '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n'


__A	:	List[Any]     =     '\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        "raw_values" : Returns a full set of errors in case of multioutput input.\n\n        "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric("mse")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {\'mse\': 0.6123724356957945}\n\n    If you\'re using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric("mse", "multilist")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mse\': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'mse\': array([0.41666667, 1. ])}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,  _KWARGS_DESCRIPTION							)
class 						__UpperCamelCase	(						datasets.Metric							):





							def 		a__   (  self		:Optional[int]			):
									return datasets.MetricInfo(
									    description=_DESCRIPTION  ,citation=_CITATION  ,inputs_description=_KWARGS_DESCRIPTION  ,features=datasets.Features(self._get_feature_types()			)  ,reference_urls=[
									        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"""
									    ]  ,)





							def 		a__   (  self		:Union[str, Any]			):
									if self.config_name == "multilist":
											return {
											    "predictions": datasets.Sequence(datasets.Value("""float"""			)			),
											    "references": datasets.Sequence(datasets.Value("""float"""			)			),
											}
									else:
											return {
											    "predictions": datasets.Value("""float"""			),
											    "references": datasets.Value("""float"""			),
											}





							def 		a__   (  self		:int  ,_UpperCamelCase		:int  ,_UpperCamelCase		:Union[str, Any]  ,_UpperCamelCase		:Any=None  ,_UpperCamelCase		:Any="uniform_average"  ,_UpperCamelCase		:Tuple=True			):
									snake_case_		:							Tuple			       =						mean_squared_error(
									    _UpperCamelCase  ,_UpperCamelCase  ,sample_weight=_UpperCamelCase  ,multioutput=_UpperCamelCase  ,squared=_UpperCamelCase			)

									return {"mse": mse}



'''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	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		List[str]   		=  KandinskyVaaPriorPipeline
							lowercase			:		Optional[Any]   		=  ['prompt']
							lowercase			:		Dict   		=  ['prompt', 'negative_prompt']
							lowercase			:		Dict   		=  [
							    'num_images_per_prompt',
							    'generator',
							    'num_inference_steps',
							    'latents',
							    'negative_prompt',
							    'guidance_scale',
							    'output_type',
							    'return_dict',
							]
							lowercase			:		int   		=  False





							@property
							def 		a__   (  self		:int			):
									return 3_2





							@property
							def 		a__   (  self		:Any			):
									return 3_2





							@property
							def 		a__   (  self		:Union[str, Any]			):
									return self.time_input_dim





							@property
							def 		a__   (  self		:int			):
									return self.time_input_dim * 4





							@property
							def 		a__   (  self		:Dict			):
									return 1_0_0





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							List[Any]			       =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
									return tokenizer





							@property
							def 		a__   (  self		:int			):
									torch.manual_seed(0			)
									snake_case_		:							Optional[Any]			       =						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-0_5  ,num_attention_heads=4  ,num_hidden_layers=5  ,pad_token_id=1  ,vocab_size=1_0_0_0  ,)
									return CLIPTextModelWithProjection(_UpperCamelCase			)





							@property
							def 		a__   (  self		:Dict			):
									torch.manual_seed(0			)

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

									snake_case_		:							int			       =						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
									snake_case_		:							Any			       =						nn.Parameter(torch.ones(model.clip_std.shape			)			)
									return model





							@property
							def 		a__   (  self		:Optional[int]			):
									torch.manual_seed(0			)
									snake_case_		:							Any			       =						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  ,)

									snake_case_		:							Optional[Any]			       =						CLIPVisionModelWithProjection(_UpperCamelCase			)
									return model





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						CLIPImageProcessor(
									    crop_size=2_2_4  ,do_center_crop=_UpperCamelCase  ,do_normalize=_UpperCamelCase  ,do_resize=_UpperCamelCase  ,image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]  ,image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]  ,resample=3  ,size=2_2_4  ,)

									return image_processor





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Tuple			       =						self.dummy_prior
									snake_case_		:							Any			       =						self.dummy_image_encoder
									snake_case_		:							Optional[int]			       =						self.dummy_text_encoder
									snake_case_		:							Any			       =						self.dummy_tokenizer
									snake_case_		:							Union[str, Any]			       =						self.dummy_image_processor

									snake_case_		:							Tuple			       =						UnCLIPScheduler(
									    variance_type="""fixed_small_log"""  ,prediction_type="""sample"""  ,num_train_timesteps=1_0_0_0  ,clip_sample=_UpperCamelCase  ,clip_sample_range=10.0  ,)

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

									return components





							def 		a__   (  self		:Dict  ,_UpperCamelCase		:str  ,_UpperCamelCase		:Union[str, Any]=0			):
									if str(_UpperCamelCase			).startswith("""mps"""			):
											snake_case_		:							Optional[int]			       =						torch.manual_seed(_UpperCamelCase			)
									else:
											snake_case_		:							int			       =						torch.Generator(device=_UpperCamelCase			).manual_seed(_UpperCamelCase			)
									snake_case_		:							Dict			       =						{
									    """prompt""": """horse""",
									    """generator""": generator,
									    """guidance_scale""": 4.0,
									    """num_inference_steps""": 2,
									    """output_type""": """np""",
									}
									return inputs





							def 		a__   (  self		:int			):
									snake_case_		:							Union[str, Any]			       =						"""cpu"""

									snake_case_		:							int			       =						self.get_dummy_components()

									snake_case_		:							int			       =						self.pipeline_class(**_UpperCamelCase			)
									snake_case_		:							Union[str, Any]			       =						pipe.to(_UpperCamelCase			)

									pipe.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Any			       =						pipe(**self.get_dummy_inputs(_UpperCamelCase			)			)
									snake_case_		:							List[Any]			       =						output.image_embeds

									snake_case_		:							List[Any]			       =						pipe(
									    **self.get_dummy_inputs(_UpperCamelCase			)  ,return_dict=_UpperCamelCase  ,)[0]

									snake_case_		:							Dict			       =						image[0, -1_0:]
									snake_case_		:							Optional[Any]			       =						image_from_tuple[0, -1_0:]

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

									snake_case_		:							Optional[int]			       =						np.array(
									    [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]			)

									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		:List[Any]			):
									snake_case_		:							Any			       =						torch_device == """cpu"""
									snake_case_		:							Any			       =						True
									snake_case_		:							Dict			       =						False

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





							@skip_mps
							def 		a__   (  self		:str			):
									snake_case_		:							str			       =						torch_device == """cpu"""
									snake_case_		:							List[str]			       =						False

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