
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 __snake_case		(      SCREAMING_SNAKE_CASE_					,	unittest.TestCase     ):
    _a		:						str=				DanceDiffusionPipeline
    _a		:						int=				UNCONDITIONAL_AUDIO_GENERATION_PARAMS
    _a		:						Union[str, Any]=				PipelineTesterMixin.required_optional_params - {
        "callback",
        "latents",
        "callback_steps",
        "output_type",
        "num_images_per_prompt",
    }
    _a		:						List[Any]=				UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
    _a		:						Optional[Any]=				False
    _a		:						Optional[int]=				False
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           torch.manual_seed(0      )
           lowercase							:     Any       	=      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=a__		,use_timestep_embedding=a__		,time_embedding_type="""fourier"""		,mid_block_type="""UNetMidBlock1D"""		,down_block_types=("""DownBlock1DNoSkip""", """DownBlock1D""", """AttnDownBlock1D""")		,up_block_types=("""AttnUpBlock1D""", """UpBlock1D""", """UpBlock1DNoSkip""")		,)
           lowercase							:     List[str]       	=      IPNDMScheduler()

           lowercase							:     Dict       	=      {
               """unet""": unet,
               """scheduler""": scheduler,
           }
           return components
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=0      ):



           '''simple docstring'''







           if str(a__      ).startswith("""mps"""      ):
                  lowercase							:     List[str]       	=      torch.manual_seed(a__      )
           else:
                  lowercase							:     Dict       	=      torch.Generator(device=a__      ).manual_seed(a__      )
           lowercase							:     Optional[Any]       	=      {
               """batch_size""": 1,
               """generator""": generator,
               """num_inference_steps""": 4,
           }
           return inputs
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      """cpu"""  # ensure determinism for the device-dependent torch.Generator
           lowercase							:     Dict       	=      self.get_dummy_components()
           lowercase							:     Union[str, Any]       	=      DanceDiffusionPipeline(**a__      )
           lowercase							:     Tuple       	=      pipe.to(a__      )
           pipe.set_progress_bar_config(disable=a__      )

           lowercase							:     Union[str, Any]       	=      self.get_dummy_inputs(a__      )
           lowercase							:     Optional[Any]       	=      pipe(**a__      )
           lowercase							:     int       	=      output.audios

           lowercase							:     List[Any]       	=      audio[0, -3:, -3:]

           assert audio.shape == (1, 2, components["unet"].sample_size)
           lowercase							:     Dict       	=      np.array([-0.7_265, 1.0_000, -0.8_388, 0.1_175, 0.9_498, -1.0_000]      )
           assert np.abs(audio_slice.flatten() - expected_slice      ).max() < 1e-2
    @skip_mps
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







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



           '''simple docstring'''







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



           '''simple docstring'''







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



           '''simple docstring'''







           return super().test_attention_slicing_forward_pass()
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().test_inference_batch_single_identical(expected_max_diff=3e-3      )






@slow
@require_torch_gpu
class __snake_case		(      unittest.TestCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     Union[str, Any]       	=      torch_device

           lowercase							:     List[str]       	=      DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""      )
           lowercase							:     List[Any]       	=      pipe.to(a__      )
           pipe.set_progress_bar_config(disable=a__      )

           lowercase							:     Optional[Any]       	=      torch.manual_seed(0      )
           lowercase							:     Union[str, Any]       	=      pipe(generator=a__		,num_inference_steps=100		,audio_length_in_s=4.096      )
           lowercase							:     Dict       	=      output.audios

           lowercase							:     Union[str, Any]       	=      audio[0, -3:, -3:]

           assert audio.shape == (1, 2, pipe.unet.sample_size)
           lowercase							:     int       	=      np.array([-0.0_192, -0.0_231, -0.0_318, -0.0_059, 0.0_002, -0.0_020]      )

           assert np.abs(audio_slice.flatten() - expected_slice      ).max() < 1e-2
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      torch_device

           lowercase							:     Tuple       	=      DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""		,torch_dtype=torch.floataa      )
           lowercase							:     str       	=      pipe.to(a__      )
           pipe.set_progress_bar_config(disable=a__      )

           lowercase							:     Dict       	=      torch.manual_seed(0      )
           lowercase							:     Optional[int]       	=      pipe(generator=a__		,num_inference_steps=100		,audio_length_in_s=4.096      )
           lowercase							:     Any       	=      output.audios

           lowercase							:     Tuple       	=      audio[0, -3:, -3:]

           assert audio.shape == (1, 2, pipe.unet.sample_size)
           lowercase							:     Tuple       	=      np.array([-0.0_367, -0.0_488, -0.0_771, -0.0_525, -0.0_444, -0.0_341]      )

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

"""simple docstring"""




from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a      :		List[Any]           =   logging.get_logger(__name__)

_a      :		Any           =   {
    'microsoft/swinv2-tiny-patch4-window8-256': (
        'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json'
    ),
}
class 						__A							( SCREAMING_SNAKE_CASE_		):
     _UpperCamelCase							:			int							=		"swinv2"

     _UpperCamelCase							:			List[str]							=		{
         "num_attention_heads": "num_heads",
         "num_hidden_layers": "num_layers",
     }






     def __init__(		self				,     a__=224				,     a__=4				,     a__=3				,     a__=96				,     a__=[2, 2, 6, 2]				,     a__=[3, 6, 12, 24]				,     a__=7				,     a__=4.0				,     a__=True				,     a__=0.0				,     a__=0.0				,     a__=0.1				,     a__="gelu"				,     a__=False				,     a__=0.0_2				,     a__=1e-5				,     a__=32				,     **a__				,     ):
       super().__init__(**a__  )

       _lowerCAmelCase						:       int  			=     image_size
       _lowerCAmelCase						:       Optional[Any]  			=     patch_size
       _lowerCAmelCase						:       Any  			=     num_channels
       _lowerCAmelCase						:       List[Any]  			=     embed_dim
       _lowerCAmelCase						:       Optional[int]  			=     depths
       _lowerCAmelCase						:       List[Any]  			=     len(a__  )
       _lowerCAmelCase						:       Any  			=     num_heads
       _lowerCAmelCase						:       Tuple  			=     window_size
       _lowerCAmelCase						:       Tuple  			=     mlp_ratio
       _lowerCAmelCase						:       Any  			=     qkv_bias
       _lowerCAmelCase						:       Optional[int]  			=     hidden_dropout_prob
       _lowerCAmelCase						:       Tuple  			=     attention_probs_dropout_prob
       _lowerCAmelCase						:       str  			=     drop_path_rate
       _lowerCAmelCase						:       List[str]  			=     hidden_act
       _lowerCAmelCase						:       List[str]  			=     use_absolute_embeddings
       _lowerCAmelCase						:       Optional[int]  			=     layer_norm_eps
       _lowerCAmelCase						:       List[Any]  			=     initializer_range
       _lowerCAmelCase						:       Any  			=     encoder_stride
       # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
       # this indicates the channel dimension after the last stage of the model
       _lowerCAmelCase						:       Tuple  			=     int(embed_dim * 2 ** (len(a__  ) - 1)  )
       _lowerCAmelCase						:       Tuple  			=     (0, 0, 0, 0)




