




from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


__A								=       logging.get_logger(__name__)  # pylint: disable=invalid-name

__A								=       "\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\")\n        >>> pipe_prior.to(\"cuda\")\n        >>> prompt = \"red cat, 4k photo\"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\")\n        >>> pipe.to(\"cuda\")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save(\"cat.png\")\n        ```\n"







def      lowerCamelCase_						(			UpperCamelCase__							: Tuple					,	UpperCamelCase__							: Tuple					,	UpperCamelCase__							: Union[str, Any]=8 )	->			int:





				"""simple docstring"""


				__lowerCamelCase									=       height // scale_factor**2
				if height % scale_factor**2 != 0:
								new_height += 1
				__lowerCamelCase									=       width // scale_factor**2
				if width % scale_factor**2 != 0:
								new_width += 1
				return new_height * scale_factor, new_width * scale_factor







class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		)       -> str:



							'''simple docstring'''
							super().__init__()

							self.register_modules(
							    unet=lowerCamelCase__     ,		scheduler=lowerCamelCase__     ,		movq=lowerCamelCase__     ,		)
							__lowerCamelCase									=       2 ** (len(self.movq.config.block_out_channels				) - 1)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> Any:



							'''simple docstring'''
							if latents is None:
											__lowerCamelCase									=       randn_tensor(lowerCamelCase__     ,		generator=lowerCamelCase__     ,		device=lowerCamelCase__     ,		dtype=lowerCamelCase__				)
							else:
											if latents.shape != shape:
															raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""				)
											__lowerCamelCase									=       latents.to(lowerCamelCase__				)

							__lowerCamelCase									=       latents * scheduler.init_noise_sigma
							return latents


			def  lowercase_       ( self     ,		lowerCamelCase__=0				)       -> Optional[Any]:



							'''simple docstring'''
							if is_accelerate_available():
											from accelerate import cpu_offload
							else:
											raise ImportError('Please install accelerate via `pip install accelerate`'				)

							__lowerCamelCase									=       torch.device(f"""cuda:{gpu_id}"""				)

							__lowerCamelCase									=       [
							    self.unet,
							    self.movq,
							]
							for cpu_offloaded_model in models:
											if cpu_offloaded_model is not None:
															cpu_offload(lowerCamelCase__     ,		lowerCamelCase__				)


			def  lowercase_       ( self     ,		lowerCamelCase__=0				)       -> Union[str, Any]:



							'''simple docstring'''
							if is_accelerate_available() and is_accelerate_version('>='     ,		'0.17.0.dev0'				):
											from accelerate import cpu_offload_with_hook
							else:
											raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'				)

							__lowerCamelCase									=       torch.device(f"""cuda:{gpu_id}"""				)

							if self.device.type != "cpu":
											self.to('cpu'     ,		silence_dtype_warnings=lowerCamelCase__				)
											torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

							__lowerCamelCase									=       None
							for cpu_offloaded_model in [self.unet, self.movq]:
											__lowerCamelCase			,		__lowerCamelCase									=       cpu_offload_with_hook(lowerCamelCase__     ,		lowerCamelCase__     ,		prev_module_hook=lowerCamelCase__				)

							# We'll offload the last model manually.
							__lowerCamelCase									=       hook


			@property
			# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							if not hasattr(self.unet     ,		'_hf_hook'				):
											return self.device
							for module in self.unet.modules():
											if (
											    hasattr(lowerCamelCase__     ,		'_hf_hook'				)
											    and hasattr(module._hf_hook     ,		'execution_device'				)
											    and module._hf_hook.execution_device is not None
											):
															return torch.device(module._hf_hook.execution_device				)
							return self.device






			@torch.no_grad()
			@replace_example_docstring(lowerCamelCase__				)
			def __call__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 512     ,		lowerCamelCase__ = 512     ,		lowerCamelCase__ = 100     ,		lowerCamelCase__ = 4.0     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = "pil"     ,		lowerCamelCase__ = True     ,		)       -> Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self._execution_device

							__lowerCamelCase									=       guidance_scale > 1.0

							if isinstance(lowerCamelCase__     ,		lowerCamelCase__				):
											__lowerCamelCase									=       torch.cat(lowerCamelCase__     ,		dim=0				)
							__lowerCamelCase									=       image_embeds.shape[0] * num_images_per_prompt
							if isinstance(lowerCamelCase__     ,		lowerCamelCase__				):
											__lowerCamelCase									=       torch.cat(lowerCamelCase__     ,		dim=0				)

							if do_classifier_free_guidance:
											__lowerCamelCase									=       image_embeds.repeat_interleave(lowerCamelCase__     ,		dim=0				)
											__lowerCamelCase									=       negative_image_embeds.repeat_interleave(lowerCamelCase__     ,		dim=0				)

							__lowerCamelCase									=       torch.cat([negative_image_embeds, image_embeds]     ,		dim=0				).to(dtype=self.unet.dtype     ,		device=lowerCamelCase__				)

							self.scheduler.set_timesteps(lowerCamelCase__     ,		device=lowerCamelCase__				)
							__lowerCamelCase									=       self.scheduler.timesteps

							__lowerCamelCase									=       self.unet.config.in_channels

							__lowerCamelCase			,		__lowerCamelCase									=       downscale_height_and_width(lowerCamelCase__     ,		lowerCamelCase__     ,		self.movq_scale_factor				)

							# create initial latent
							__lowerCamelCase									=       self.prepare_latents(
							    (batch_size, num_channels_latents, height, width)     ,		image_embeds.dtype     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		self.scheduler     ,		)

							for i, t in enumerate(self.progress_bar(lowerCamelCase__				)				):
											# expand the latents if we are doing classifier free guidance
											__lowerCamelCase									=       torch.cat([latents] * 2				) if do_classifier_free_guidance else latents

											__lowerCamelCase									=       {'image_embeds': image_embeds}
											__lowerCamelCase									=       self.unet(
											    sample=lowerCamelCase__     ,		timestep=lowerCamelCase__     ,		encoder_hidden_states=lowerCamelCase__     ,		added_cond_kwargs=lowerCamelCase__     ,		return_dict=lowerCamelCase__     ,		)[0]

											if do_classifier_free_guidance:
															__lowerCamelCase			,		__lowerCamelCase									=       noise_pred.split(latents.shape[1]     ,		dim=1				)
															__lowerCamelCase			,		__lowerCamelCase									=       noise_pred.chunk(2				)
															__lowerCamelCase			,		__lowerCamelCase									=       variance_pred.chunk(2				)
															__lowerCamelCase									=       noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
															__lowerCamelCase									=       torch.cat([noise_pred, variance_pred_text]     ,		dim=1				)

											if not (
											    hasattr(self.scheduler.config     ,		'variance_type'				)
											    and self.scheduler.config.variance_type in ["learned", "learned_range"]
											):
															__lowerCamelCase			,		__lowerCamelCase									=       noise_pred.split(latents.shape[1]     ,		dim=1				)

											# compute the previous noisy sample x_t -> x_t-1
											__lowerCamelCase									=       self.scheduler.step(
											    lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		generator=lowerCamelCase__     ,		)[0]
							# post-processing
							__lowerCamelCase									=       self.movq.decode(lowerCamelCase__     ,		force_not_quantize=lowerCamelCase__				)['sample']

							if output_type not in ["pt", "np", "pil"]:
											raise ValueError(f"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"""				)

							if output_type in ["np", "pil"]:
											__lowerCamelCase									=       image * 0.5 + 0.5
											__lowerCamelCase									=       image.clamp(0     ,		1				)
											__lowerCamelCase									=       image.cpu().permute(0     ,		2     ,		3     ,		1				).float().numpy()

							if output_type == "pil":
											__lowerCamelCase									=       self.numpy_to_pil(lowerCamelCase__				)

							if not return_dict:
											return (image,)

							return ImagePipelineOutput(images=lowerCamelCase__				)








from sklearn.metrics import mean_squared_error

import datasets


__A								=       "\\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								=       "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n"


__A								=       "\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        __lowerCAmelCase					(			datasets.Metric					):

			"""simple docstring"""







			def  lowercase_       ( self				)       -> Union[str, Any]:



							'''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				)       -> Tuple:



							'''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     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__=None     ,		lowerCamelCase__="uniform_average"     ,		lowerCamelCase__=True				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       mean_squared_error(
							    lowerCamelCase__     ,		lowerCamelCase__     ,		sample_weight=lowerCamelCase__     ,		multioutput=lowerCamelCase__     ,		squared=lowerCamelCase__				)

							return {"mse": mse}


