





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 		_A(   SCREAMING_SNAKE_CASE_							,					unittest.TestCase  ):


				"""simple docstring"""


				UpperCamelCase       :    int          =      DanceDiffusionPipeline
				UpperCamelCase       :    Dict          =      UNCONDITIONAL_AUDIO_GENERATION_PARAMS
				UpperCamelCase       :    Tuple          =      PipelineTesterMixin.required_optional_params - {
				    '''callback''',
				    '''latents''',
				    '''callback_steps''',
				    '''output_type''',
				    '''num_images_per_prompt''',
				}
				UpperCamelCase       :    Tuple          =      UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
				UpperCamelCase       :    Union[str, Any]          =      False
				UpperCamelCase       :    Dict          =      False



				def    UpperCAmelCase_						(     self	):
									torch.manual_seed(0	)
									__A      :		Dict         =							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=__snake_case	,   use_timestep_embedding=__snake_case	,   time_embedding_type='fourier'	,   mid_block_type='UNetMidBlock1D'	,   down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')	,   up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')	,   )
									__A      :		Tuple         =							IPNDMScheduler()

									__A      :		Union[str, Any]         =							{
									    """unet""": unet,
									    """scheduler""": scheduler,
									}
									return components



				def    UpperCAmelCase_						(     self	,   _A	,   _A=0	):
									if str(__snake_case	).startswith('mps'	):
														__A      :		List[str]         =							torch.manual_seed(__snake_case	)
									else:
														__A      :		Union[str, Any]         =							torch.Generator(device=__snake_case	).manual_seed(__snake_case	)
									__A      :		int         =							{
									    """batch_size""": 1,
									    """generator""": generator,
									    """num_inference_steps""": 4,
									}
									return inputs



				def    UpperCAmelCase_						(     self	):
									__A      :		int         =							"""cpu"""  # ensure determinism for the device-dependent torch.Generator
									__A      :		List[Any]         =							self.get_dummy_components()
									__A      :		Dict         =							DanceDiffusionPipeline(**__snake_case	)
									__A      :		List[str]         =							pipe.to(__snake_case	)
									pipe.set_progress_bar_config(disable=__snake_case	)

									__A      :		Union[str, Any]         =							self.get_dummy_inputs(__snake_case	)
									__A      :		Any         =							pipe(**__snake_case	)
									__A      :		int         =							output.audios

									__A      :		Optional[int]         =							audio[0, -3:, -3:]

									assert audio.shape == (1, 2, components["unet"].sample_size)
									__A      :		Optional[Any]         =							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	):
									return super().test_save_load_local()



				@skip_mps
				def    UpperCAmelCase_						(     self	):
									return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3	)



				@skip_mps
				def    UpperCAmelCase_						(     self	):
									return super().test_save_load_optional_components()



				@skip_mps
				def    UpperCAmelCase_						(     self	):
									return super().test_attention_slicing_forward_pass()





				def    UpperCAmelCase_						(     self	):
									super().test_inference_batch_single_identical(expected_max_diff=3e-3	)





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


				"""simple docstring"""


				def    UpperCAmelCase_						(     self	):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()



				def    UpperCAmelCase_						(     self	):
									__A      :		Tuple         =							torch_device

									__A      :		Union[str, Any]         =							DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'	)
									__A      :		Optional[Any]         =							pipe.to(__snake_case	)
									pipe.set_progress_bar_config(disable=__snake_case	)

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

									__A      :		Optional[int]         =							audio[0, -3:, -3:]

									assert audio.shape == (1, 2, pipe.unet.sample_size)
									__A      :		int         =							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	):
									__A      :		int         =							torch_device

									__A      :		List[Any]         =							DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'	,   torch_dtype=torch.floataa	)
									__A      :		List[str]         =							pipe.to(__snake_case	)
									pipe.set_progress_bar_config(disable=__snake_case	)

									__A      :		Tuple         =							torch.manual_seed(0	)
									__A      :		List[Any]         =							pipe(generator=__snake_case	,   num_inference_steps=100	,   audio_length_in_s=4.0_9_6	)
									__A      :		str         =							output.audios

									__A      :		Optional[Any]         =							audio[0, -3:, -3:]

									assert audio.shape == (1, 2, pipe.unet.sample_size)
									__A      :		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












"""simple docstring"""





from typing import Union

import fire
import torch
from tqdm import tqdm



def   a    (     __UpperCAmelCase      :    str      ,   __UpperCAmelCase      :    str = "cpu"      ,   __UpperCAmelCase      :    Union[str, None] = None  )    ->							None:
						__magic_name__:	List[Any]							=       torch.load(__UpperCAmelCase      ,   map_location=__UpperCAmelCase  )
						for k, v in tqdm(state_dict.items()  ):
												if not isinstance(__UpperCAmelCase      ,   torch.Tensor  ):
																		raise TypeError("""FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin"""  )
												__magic_name__:	Any							=       v.half()
						if save_path is None:  # overwrite src_path
												__magic_name__:	List[str]							=       src_path
						torch.save(__UpperCAmelCase      ,   __UpperCAmelCase  )


if __name__ == "__main__":
							fire.Fire(convert)



