



'''simple docstring'''
import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


snake_case_			:     Union[str, Any]  	=  logging.get_logger(__name__)






def A__   (					UpperCAmelCase_=None  ,  UpperCAmelCase_=None							):






						"""simple docstring"""




						return field(default_factory=lambda: default  ,  metadata=UpperCAmelCase_							)






@dataclass
class 							lowercase__     :
	lowercase__      =      list_field(
	    default=[]						, metadata={
	        """help""": (
	            """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
	            """ of all available models"""
	        )
	    }						, )

	lowercase__      =      list_field(
	    default=[8]						, metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}       )

	lowercase__      =      list_field(
	    default=[8, 32, 1_28, 5_12]						, metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""}						, )

	lowercase__      =      field(
	    default=lowercase						, metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""}						, )
	lowercase__      =      field(
	    default=lowercase						, metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""}						, )
	lowercase__      =      field(
	    default=lowercase						, metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Use FP16 to accelerate inference."""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Benchmark training of model"""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Verbose memory tracing"""}       )
	lowercase__      =      field(
	    default=lowercase						, metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""}						, )
	lowercase__      =      field(
	    default=lowercase						, metadata={
	        """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
	    }						, )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Trace memory line by line"""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Save result to a CSV file"""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Save all print statements in a log file"""}       )
	lowercase__      =      field(default=lowercase						, metadata={"""help""": """Whether to print environment information"""}       )
	lowercase__      =      field(
	    default=lowercase						, metadata={
	        """help""": (
	            """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
	            """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
	            """ for debugging / testing and on TPU."""
	        )
	    }						, )
	lowercase__      =      field(
	    default=f"""inference_time_{round(time()       )}.csv"""						, metadata={"""help""": """CSV filename used if saving time results to csv."""}						, )
	lowercase__      =      field(
	    default=f"""inference_memory_{round(time()       )}.csv"""						, metadata={"""help""": """CSV filename used if saving memory results to csv."""}						, )
	lowercase__      =      field(
	    default=f"""train_time_{round(time()       )}.csv"""						, metadata={"""help""": """CSV filename used if saving time results to csv for training."""}						, )
	lowercase__      =      field(
	    default=f"""train_memory_{round(time()       )}.csv"""						, metadata={"""help""": """CSV filename used if saving memory results to csv for training."""}						, )
	lowercase__      =      field(
	    default=f"""env_info_{round(time()       )}.csv"""						, metadata={"""help""": """CSV filename used if saving environment information."""}						, )
	lowercase__      =      field(
	    default=f"""log_{round(time()       )}.csv"""						, metadata={"""help""": """Log filename used if print statements are saved in log."""}						, )
	lowercase__      =      field(default=3						, metadata={"""help""": """Times an experiment will be run."""}       )
	lowercase__      =      field(
	    default=lowercase						, metadata={
	        """help""": (
	            """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
	            """ model weights."""
	        )
	    }						, )





	def      UpperCamelCase_  (			self :    List[Any]			):







							'''simple docstring'''
							warnings.warn(
							    F'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
							    ' are deprecated in general and it is advised to use external Benchmarking libraries '
							    ' to benchmark Transformer models.'			,lowerCamelCase__			,)





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







							'''simple docstring'''
							return json.dumps(dataclasses.asdict(self			)			,indent=2			)





	@property
	def      UpperCamelCase_  (			self :    List[str]			):







							'''simple docstring'''




							if len(self.models			) <= 0:
													raise ValueError(
													    'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
													    ' bert-base-cased` or `args.models = [\'bert-base-cased\'].'			)
							return self.models





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







							'''simple docstring'''




							if not self.multi_process:
													return False
							elif self.is_tpu:
													logger.info('Multiprocessing is currently not possible on TPU.'			)
													return False
							else:
													return True







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


