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




		"""simple docstring"""





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




		def 	snake_case_     (     self):
				torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = UNetaDModel(
				    block_out_channels=(3_2, 3_2, 6_4)							,  extra_in_channels=1_6							,  sample_size=5_1_2							,  sample_rate=1_6_0_0_0							,  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""")							,  )
				__SCREAMING_SNAKE_CASE            = IPNDMScheduler()

				__SCREAMING_SNAKE_CASE            = {
				    """unet""": unet,
				    """scheduler""": scheduler,
				}
				return components




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=0):
				if str(lowerCAmelCase__).startswith("""mps"""):
						__SCREAMING_SNAKE_CASE            = torch.manual_seed(lowerCAmelCase__)
				else:
						__SCREAMING_SNAKE_CASE            = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = {
				    """batch_size""": 1,
				    """generator""": generator,
				    """num_inference_steps""": 4,
				}
				return inputs




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = """cpu"""  # ensure determinism for the device-dependent torch.Generator
				__SCREAMING_SNAKE_CASE            = self.get_dummy_components()
				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.get_dummy_inputs(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, components["unet"].sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.72_65, 1.00_00, -0.83_88, 0.11_75, 0.94_98, -1.00_00])
				assert np.abs(audio_slice.flatten() - expected_slice).max() < 1E-2




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_save_load_local()




		@skip_mps
		def 	snake_case_     (     self):
				return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3)




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




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




		def 	snake_case_     (     self):
				super().test_inference_batch_single_identical(expected_max_diff=3E-3)



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




		"""simple docstring"""





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




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = torch_device

				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k""")
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = pipe(generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  audio_length_in_s=4.0_96)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, pipe.unet.sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.01_92, -0.02_31, -0.03_18, -0.00_59, 0.00_02, -0.00_20])

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




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = torch_device

				__SCREAMING_SNAKE_CASE            = DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""							,  torch_dtype=torch.floataa)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)
				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = pipe(generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  audio_length_in_s=4.0_96)
				__SCREAMING_SNAKE_CASE            = output.audios

				__SCREAMING_SNAKE_CASE            = audio[0, -3:, -3:]

				assert audio.shape == (1, 2, pipe.unet.sample_size)
				__SCREAMING_SNAKE_CASE            = np.array([-0.03_67, -0.04_88, -0.07_71, -0.05_25, -0.04_44, -0.03_41])

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











"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_     :						str						=					logging.get_logger(__name__)

lowerCamelCase_     :						Any						=					{
    'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
    'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
    'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
    'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
    'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
    'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
    'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
    'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
    'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : Tuple	    =   """xmod"""

      def __init__(     self					,      snake_case_=3_0_5_2_2					,      snake_case_=7_6_8					,      snake_case_=1_2					,      snake_case_=1_2					,      snake_case_=3_0_7_2					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=5_1_2					,      snake_case_=2					,      snake_case_=0.02					,      snake_case_=1E-12					,      snake_case_=1					,      snake_case_=0					,      snake_case_=2					,      snake_case_="absolute"					,      snake_case_=True					,      snake_case_=None					,      snake_case_=False					,      snake_case_=2					,      snake_case_=False					,      snake_case_=True					,      snake_case_=True					,      snake_case_=("en_XX",)					,      snake_case_=None					,      **snake_case_					,      ):

        """simple docstring"""

        super().__init__(pad_token_id=snake_case_					,      bos_token_id=snake_case_					,      eos_token_id=snake_case_					,      **snake_case_  )

        A_  :       Union[str, Any]										=  vocab_size
        A_  :       Any										=  hidden_size
        A_  :       List[str]										=  num_hidden_layers
        A_  :       Tuple										=  num_attention_heads
        A_  :       int										=  hidden_act
        A_  :       Any										=  intermediate_size
        A_  :       Any										=  hidden_dropout_prob
        A_  :       Dict										=  attention_probs_dropout_prob
        A_  :       Union[str, Any]										=  max_position_embeddings
        A_  :       List[Any]										=  type_vocab_size
        A_  :       List[str]										=  initializer_range
        A_  :       Any										=  layer_norm_eps
        A_  :       Optional[Any]										=  position_embedding_type
        A_  :       int										=  use_cache
        A_  :       Dict										=  classifier_dropout
        A_  :       int										=  pre_norm
        A_  :       Optional[Any]										=  adapter_reduction_factor
        A_  :       List[Any]										=  adapter_layer_norm
        A_  :       int										=  adapter_reuse_layer_norm
        A_  :       Dict										=  ln_before_adapter
        A_  :       List[str]										=  list(snake_case_  )
        A_  :       Union[str, Any]										=  default_language


class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        if self.task == "multiple-choice":
          A_  :       Dict										=  {0: 'batch', 1: 'choice', 2: 'sequence'}
        else:
          A_  :       int										=  {0: 'batch', 1: 'sequence'}
        return OrderedDict(
            [
                ('input_ids', dynamic_axis),
                ('attention_mask', dynamic_axis),
            ]  )