



'''simple docstring'''
import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
					import torch_xla.core.xla_model as xm
					import torch_xla.debug.metrics as met






class 							lowercase__     (							lowercase       ):





	def __init__(			self :    Optional[Any]			,*lowerCamelCase__ :    Any			,lowerCamelCase__ :    Union[str, Any]=None			,lowerCamelCase__ :    str=None			,**lowerCamelCase__ :    List[Any]			):







							'''simple docstring'''
							super().__init__(*lowerCamelCase__			,**lowerCamelCase__			)
							_UpperCamelCase :		Any			    =       eval_examples
							_UpperCamelCase :		Optional[int]			    =       post_process_function





	def      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    Optional[Dataset] = None			,lowerCamelCase__ :    List[Any]=None			,lowerCamelCase__ :    Optional[List[str]] = None			,lowerCamelCase__ :    str = "eval"			,**lowerCamelCase__ :    Any			,):







							'''simple docstring'''
							_UpperCamelCase :		Optional[int]			    =       gen_kwargs.copy()
							_UpperCamelCase :		int			    =       (
							    gen_kwargs['max_length'] if gen_kwargs.get('max_length'			) is not None else self.args.generation_max_length
							)
							_UpperCamelCase :		Union[str, Any]			    =       (
							    gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'			) is not None else self.args.generation_num_beams
							)
							_UpperCamelCase :		str			    =       gen_kwargs

							_UpperCamelCase :		List[str]			    =       self.eval_dataset if eval_dataset is None else eval_dataset
							_UpperCamelCase :		Tuple			    =       self.get_eval_dataloader(lowerCamelCase__			)
							_UpperCamelCase :		Optional[Any]			    =       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							_UpperCamelCase :		Dict			    =       self.compute_metrics
							_UpperCamelCase :		str			    =       None
							_UpperCamelCase :		Optional[int]			    =       time.time()
							_UpperCamelCase :		Any			    =       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													_UpperCamelCase :		Any			    =       eval_loop(
													    lowerCamelCase__			,description='Evaluation'			,prediction_loss_only=True if compute_metrics is None else None			,ignore_keys=lowerCamelCase__			,metric_key_prefix=lowerCamelCase__			,)
							finally:
													_UpperCamelCase :		Optional[int]			    =       compute_metrics
							_UpperCamelCase :		str			    =       self.args.eval_batch_size * self.args.world_size
							if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
													start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
							output.metrics.update(
							    speed_metrics(
							        lowerCamelCase__			,lowerCamelCase__			,num_samples=output.num_samples			,num_steps=math.ceil(output.num_samples / total_batch_size			)			,)			)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													_UpperCamelCase :		int			    =       self.post_process_function(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			)
													_UpperCamelCase :		int			    =       self.compute_metrics(lowerCamelCase__			)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()			):
																			if not key.startswith(F'{metric_key_prefix}_'			):
																									_UpperCamelCase :		List[Any]			    =       metrics.pop(lowerCamelCase__			)

													metrics.update(output.metrics			)
							else:
													_UpperCamelCase :		Tuple			    =       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(lowerCamelCase__			)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()			)

							_UpperCamelCase :		Union[str, Any]			    =       self.callback_handler.on_evaluate(self.args			,self.state			,self.control			,lowerCamelCase__			)
							return metrics





	def      UpperCamelCase_  (			self :    int			,lowerCamelCase__ :    Optional[Any]			,lowerCamelCase__ :    Optional[int]			,lowerCamelCase__ :    Dict=None			,lowerCamelCase__ :    str = "test"			,**lowerCamelCase__ :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		int			    =       gen_kwargs.copy()

							_UpperCamelCase :		List[Any]			    =       self.get_test_dataloader(lowerCamelCase__			)

							# Temporarily disable metric computation, we will do it in the loop here.
							_UpperCamelCase :		str			    =       self.compute_metrics
							_UpperCamelCase :		int			    =       None
							_UpperCamelCase :		int			    =       time.time()
							_UpperCamelCase :		int			    =       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													_UpperCamelCase :		Optional[Any]			    =       eval_loop(
													    lowerCamelCase__			,description='Prediction'			,prediction_loss_only=True if compute_metrics is None else None			,ignore_keys=lowerCamelCase__			,metric_key_prefix=lowerCamelCase__			,)
							finally:
													_UpperCamelCase :		Tuple			    =       compute_metrics

							_UpperCamelCase :		Union[str, Any]			    =       self.args.eval_batch_size * self.args.world_size
							if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
													start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
							output.metrics.update(
							    speed_metrics(
							        lowerCamelCase__			,lowerCamelCase__			,num_samples=output.num_samples			,num_steps=math.ceil(output.num_samples / total_batch_size			)			,)			)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							_UpperCamelCase :		Dict			    =       self.post_process_function(lowerCamelCase__			,lowerCamelCase__			,lowerCamelCase__			,'predict'			)
							_UpperCamelCase :		Optional[Any]			    =       self.compute_metrics(lowerCamelCase__			)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()			):
													if not key.startswith(F'{metric_key_prefix}_'			):
																			_UpperCamelCase :		Dict			    =       metrics.pop(lowerCamelCase__			)
							metrics.update(output.metrics			)
							return PredictionOutput(predictions=predictions.predictions			,label_ids=predictions.label_ids			,metrics=lowerCamelCase__			)







'''simple docstring'''
import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class 							lowercase__     (							lowercase						, unittest.TestCase       ):
	lowercase__      =      DanceDiffusionPipeline
	lowercase__      =      UNCONDITIONAL_AUDIO_GENERATION_PARAMS
	lowercase__      =      PipelineTesterMixin.required_optional_params - {
	    """callback""",
	    """latents""",
	    """callback_steps""",
	    """output_type""",
	    """num_images_per_prompt""",
	}
	lowercase__      =      UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
	lowercase__      =      False
	lowercase__      =      False





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							torch.manual_seed(0			)
							_UpperCamelCase :		str			    =       UNetaDModel(
							    block_out_channels=(32, 32, 64)			,extra_in_channels=16			,sample_size=512			,sample_rate=16000			,in_channels=2			,out_channels=2			,flip_sin_to_cos=lowerCamelCase__			,use_timestep_embedding=lowerCamelCase__			,time_embedding_type='fourier'			,mid_block_type='UNetMidBlock1D'			,down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')			,up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')			,)
							_UpperCamelCase :		int			    =       IPNDMScheduler()

							_UpperCamelCase :		List[str]			    =       {
							    'unet': unet,
							    'scheduler': scheduler,
							}
							return components





	def      UpperCamelCase_  (			self :    Tuple			,lowerCamelCase__ :    Tuple			,lowerCamelCase__ :    int=0			):







							'''simple docstring'''
							if str(lowerCamelCase__			).startswith('mps'			):
													_UpperCamelCase :		Union[str, Any]			    =       torch.manual_seed(lowerCamelCase__			)
							else:
													_UpperCamelCase :		str			    =       torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
							_UpperCamelCase :		str			    =       {
							    'batch_size': 1,
							    'generator': generator,
							    'num_inference_steps': 4,
							}
							return inputs





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
							_UpperCamelCase :		List[str]			    =       self.get_dummy_components()
							_UpperCamelCase :		int			    =       DanceDiffusionPipeline(**lowerCamelCase__			)
							_UpperCamelCase :		List[str]			    =       pipe.to(lowerCamelCase__			)
							pipe.set_progress_bar_config(disable=lowerCamelCase__			)

							_UpperCamelCase :		Union[str, Any]			    =       self.get_dummy_inputs(lowerCamelCase__			)
							_UpperCamelCase :		List[Any]			    =       pipe(**lowerCamelCase__			)
							_UpperCamelCase :		Union[str, Any]			    =       output.audios

							_UpperCamelCase :		List[str]			    =       audio[0, -3:, -3:]

							assert audio.shape == (1, 2, components["unet"].sample_size)
							_UpperCamelCase :		Dict			    =       np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0]			)
							assert np.abs(audio_slice.flatten() - expected_slice			).max() < 1E-2





	@skip_mps
	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							return super().test_save_load_local()





	@skip_mps
	def      UpperCamelCase_  (			self :    Dict			):







							'''simple docstring'''
							return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3			)





	@skip_mps
	def      UpperCamelCase_  (			self :    str			):







							'''simple docstring'''
							return super().test_save_load_optional_components()





	@skip_mps
	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							return super().test_attention_slicing_forward_pass()





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							super().test_inference_batch_single_identical(expected_max_diff=3E-3			)






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





	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()





	def      UpperCamelCase_  (			self :    int			):







							'''simple docstring'''
							_UpperCamelCase :		Union[str, Any]			    =       torch_device

							_UpperCamelCase :		Dict			    =       DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'			)
							_UpperCamelCase :		str			    =       pipe.to(lowerCamelCase__			)
							pipe.set_progress_bar_config(disable=lowerCamelCase__			)

							_UpperCamelCase :		int			    =       torch.manual_seed(0			)
							_UpperCamelCase :		Optional[Any]			    =       pipe(generator=lowerCamelCase__			,num_inference_steps=100			,audio_length_in_s=4.0_9_6			)
							_UpperCamelCase :		Optional[int]			    =       output.audios

							_UpperCamelCase :		int			    =       audio[0, -3:, -3:]

							assert audio.shape == (1, 2, pipe.unet.sample_size)
							_UpperCamelCase :		Tuple			    =       np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0]			)

							assert np.abs(audio_slice.flatten() - expected_slice			).max() < 1E-2





	def      UpperCamelCase_  (			self :    Union[str, Any]			):







							'''simple docstring'''
							_UpperCamelCase :		List[Any]			    =       torch_device

							_UpperCamelCase :		int			    =       DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'			,torch_dtype=torch.floataa			)
							_UpperCamelCase :		Any			    =       pipe.to(lowerCamelCase__			)
							pipe.set_progress_bar_config(disable=lowerCamelCase__			)

							_UpperCamelCase :		Union[str, Any]			    =       torch.manual_seed(0			)
							_UpperCamelCase :		Union[str, Any]			    =       pipe(generator=lowerCamelCase__			,num_inference_steps=100			,audio_length_in_s=4.0_9_6			)
							_UpperCamelCase :		Any			    =       output.audios

							_UpperCamelCase :		str			    =       audio[0, -3:, -3:]

							assert audio.shape == (1, 2, pipe.unet.sample_size)
							_UpperCamelCase :		Any			    =       np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1]			)

							assert np.abs(audio_slice.flatten() - expected_slice			).max() < 1E-2


