



"""simple docstring"""







import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
			import onnxruntime as ort






class       UpperCamelCase__			(   _SCREAMING_SNAKE_CASE       ,		unittest.TestCase      ):

			"""simple docstring"""


			A__	:					Optional[int]							  =     '''ssube/stable-diffusion-x4-upscaler-onnx'''


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__=0		)      ->	Union[str, Any]:
				A__											=					floats_tensor((1, 3, 128, 128)						,	rng=random.Random(_lowercase		)		)
				A__											=					torch.manual_seed(_lowercase		)
				A__											=					{
				    "prompt": "A painting of a squirrel eating a burger",
				    "image": image,
				    "generator": generator,
				    "num_inference_steps": 3,
				    "guidance_scale": 7.5,
				    "output_type": "numpy",
				}
				return inputs


			def   snake_case__	(      self		)      ->	Union[str, Any]:
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"		)
				pipe.set_progress_bar_config(disable=_lowercase		)

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

				# started as 128, should now be 512
				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]		)
				assert np.abs(image_slice - expected_slice		).max() < 1e-1


			def   snake_case__	(      self		)      ->	Dict:
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"		)
				A__											=					PNDMScheduler.from_config(pipe.scheduler.config						,	skip_prk_steps=_lowercase		)
				pipe.set_progress_bar_config(disable=_lowercase		)

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

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4]		)
				assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1


			def   snake_case__	(      self		)      ->	List[Any]:
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"		)
				A__											=					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
				pipe.set_progress_bar_config(disable=_lowercase		)

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

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5]		)

				assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1


			def   snake_case__	(      self		)      ->	Union[str, Any]:
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"		)
				A__											=					EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
				pipe.set_progress_bar_config(disable=_lowercase		)

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

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]		)
				assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1







			def   snake_case__	(      self		)      ->	Optional[Any]:
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"		)
				A__											=					EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
				pipe.set_progress_bar_config(disable=_lowercase		)

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

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3]		)

				assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1






@nightly
@require_onnxruntime
@require_torch_gpu
class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			@property
			def   snake_case__	(      self		)      ->	Optional[int]:
				return (
				    "CUDAExecutionProvider",
				    {
				        "gpu_mem_limit": "15000000000",  # 15GB
				        "arena_extend_strategy": "kSameAsRequested",
				    },
				)


			@property
			def   snake_case__	(      self		)      ->	str:
				A__											=					ort.SessionOptions()
				A__											=					False
				return options


			def   snake_case__	(      self		)      ->	str:
				A__											=					load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
				    "/img2img/sketch-mountains-input.jpg"		)
				A__											=					init_image.resize((128, 128)		)
				# using the PNDM scheduler by default
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(
				    "ssube/stable-diffusion-x4-upscaler-onnx"						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
				pipe.set_progress_bar_config(disable=_lowercase		)

				A__											=					"A fantasy landscape, trending on artstation"

				A__											=					torch.manual_seed(0		)
				A__											=					pipe(
				    prompt=_lowercase						,	image=_lowercase						,	guidance_scale=7.5						,	num_inference_steps=10						,	generator=_lowercase						,	output_type="np"						,	)
				A__											=					output.images
				A__											=					images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 512, 3)
				A__											=					np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2]		)
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

				assert np.abs(image_slice.flatten() - expected_slice		).max() < 2e-2







			def   snake_case__	(      self		)      ->	Optional[int]:
				A__											=					load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
				    "/img2img/sketch-mountains-input.jpg"		)
				A__											=					init_image.resize((128, 128)		)
				A__											=					LMSDiscreteScheduler.from_pretrained(
				    "ssube/stable-diffusion-x4-upscaler-onnx"						,	subfolder="scheduler"		)
				A__											=					OnnxStableDiffusionUpscalePipeline.from_pretrained(
				    "ssube/stable-diffusion-x4-upscaler-onnx"						,	scheduler=_lowercase						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
				pipe.set_progress_bar_config(disable=_lowercase		)

				A__											=					"A fantasy landscape, trending on artstation"

				A__											=					torch.manual_seed(0		)
				A__											=					pipe(
				    prompt=_lowercase						,	image=_lowercase						,	guidance_scale=7.5						,	num_inference_steps=20						,	generator=_lowercase						,	output_type="np"						,	)
				A__											=					output.images
				A__											=					images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 512, 3)
				A__											=					np.array(
				    [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6]		)
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

				assert np.abs(image_slice.flatten() - expected_slice		).max() < 2e-2






'''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}
