
'''simple docstring'''



import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE			,				unittest.TestCase					):






						'''simple docstring'''






						_lowercase						: Optional[Any]										=  DiTPipeline
						_lowercase						: List[Any]										=  CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
						_lowercase						: List[Any]										=  PipelineTesterMixin.required_optional_params - {
						    '''latents''',
						    '''num_images_per_prompt''',
						    '''callback''',
						    '''callback_steps''',
						}
						_lowercase						: Optional[Any]										=  CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
						_lowercase						: Optional[int]										=  False




						def    _lowercase      (   self ):

												"""simple docstring"""



												torch.manual_seed(0 )
												_lowerCAmelCase    		=					TransformeraDModel(
												    sample_size=16       ,  num_layers=2       ,  patch_size=4       ,  attention_head_dim=8       ,  num_attention_heads=2       ,  in_channels=4       ,  out_channels=8       ,  attention_bias=_lowercase       ,  activation_fn="""gelu-approximate"""       ,  num_embeds_ada_norm=1_000       ,  norm_type="""ada_norm_zero"""       ,  norm_elementwise_affine=_lowercase       ,  )
												_lowerCAmelCase    		=					AutoencoderKL()
												_lowerCAmelCase    		=					DDIMScheduler()
												_lowerCAmelCase    		=					{"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
												return components




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase=0 ):

												"""simple docstring"""



												if str(_lowercase ).startswith("""mps""" ):
																		_lowerCAmelCase    		=					torch.manual_seed(_lowercase )
												else:
																		_lowerCAmelCase    		=					torch.Generator(device=_lowercase ).manual_seed(_lowercase )
												_lowerCAmelCase    		=					{
												    """class_labels""": [1],
												    """generator""": generator,
												    """num_inference_steps""": 2,
												    """output_type""": """numpy""",
												}
												return inputs




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					"""cpu"""

												_lowerCAmelCase    		=					self.get_dummy_components()
												_lowerCAmelCase    		=					self.pipeline_class(**_lowercase )
												pipe.to(_lowercase )
												pipe.set_progress_bar_config(disable=_lowercase )

												_lowerCAmelCase    		=					self.get_dummy_inputs(_lowercase )
												_lowerCAmelCase    		=					pipe(**_lowercase ).images
												_lowerCAmelCase    		=					image[0, -3:, -3:, -1]

												self.assertEqual(image.shape       ,  (1, 16, 16, 3) )
												_lowerCAmelCase    		=					np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] )
												_lowerCAmelCase    		=					np.abs(image_slice.flatten() - expected_slice ).max()
												self.assertLessEqual(_lowercase       ,  1e-3 )




						def    _lowercase      (   self ):

												"""simple docstring"""



												self._test_inference_batch_single_identical(relax_max_difference=_lowercase       ,  expected_max_diff=1e-3 )




						@unittest.skipIf(
						    torch_device != """cuda""" or not is_xformers_available()       ,  reason="""XFormers attention is only available with CUDA and `xformers` installed"""       ,  )
						def    _lowercase      (   self ):

												"""simple docstring"""



												self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 )






@require_torch_gpu
@slow
class     UpperCAmelCase_	(						unittest.TestCase					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""simple docstring"""



												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					torch.manual_seed(0 )

												_lowerCAmelCase    		=					DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" )
												pipe.to("""cuda""" )

												_lowerCAmelCase    		=					["""vase""", """umbrella""", """white shark""", """white wolf"""]
												_lowerCAmelCase    		=					pipe.get_label_ids(_lowercase )

												_lowerCAmelCase    		=					pipe(_lowercase       ,  generator=_lowercase       ,  num_inference_steps=40       ,  output_type="""np""" ).images

												for word, image in zip(_lowercase       ,  _lowercase ):
																		_lowerCAmelCase    		=					load_numpy(
																		    F'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' )
																		assert np.abs((expected_image - image).max() ) < 1e-2




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" )
												_lowerCAmelCase    		=					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
												pipe.to("""cuda""" )

												_lowerCAmelCase    		=					["""vase""", """umbrella"""]
												_lowerCAmelCase    		=					pipe.get_label_ids(_lowercase )

												_lowerCAmelCase    		=					torch.manual_seed(0 )
												_lowerCAmelCase    		=					pipe(_lowercase       ,  generator=_lowercase       ,  num_inference_steps=25       ,  output_type="""np""" ).images

												for word, image in zip(_lowercase       ,  _lowercase ):
																		_lowerCAmelCase    		=					load_numpy(
																		    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
																		    F'/dit/{word}_512.npy' )

																		assert np.abs((expected_image - image).max() ) < 1e-1


'''simple docstring'''



from sklearn.metrics import mean_squared_error

import datasets


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

_lowercase          =						"""\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


_lowercase          =						"""
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        \"raw_values\" : Returns a full set of errors in case of multioutput input.

        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric(\"mse\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {'mse': 0.6123724356957945}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'mse': array([0.41666667, 1. ])}
"""




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,				_KWARGS_DESCRIPTION					)
class     UpperCAmelCase_	(						datasets.Metric					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""simple docstring"""



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

												"""simple docstring"""



												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    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase=None       ,  _lowercase="uniform_average"       ,  _lowercase=True ):

												"""simple docstring"""



												_lowerCAmelCase    		=					mean_squared_error(
												    _lowercase       ,  _lowercase       ,  sample_weight=_lowercase       ,  multioutput=_lowercase       ,  squared=_lowercase )

												return {"mse": mse}
