



"""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        _UpperCAmelCase       (			lowerCAmelCase__    ,     unittest.TestCase):
 _lowerCAmelCase   :			List[str]							=		DanceDiffusionPipeline
 _lowerCAmelCase   :			Tuple							=		UNCONDITIONAL_AUDIO_GENERATION_PARAMS
 _lowerCAmelCase   :			int							=		PipelineTesterMixin.required_optional_params - {
     """callback""",
     """latents""",
     """callback_steps""",
     """output_type""",
     """num_images_per_prompt""",
 }
 _lowerCAmelCase   :			Optional[Any]							=		UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
 _lowerCAmelCase   :			Any							=		False
 _lowerCAmelCase   :			List[Any]							=		False

 def 						_snake_case					(     self		:       List[str]				):
     torch.manual_seed(0				)
     snake_case_ :     Tuple				=	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=lowercase_  ,     use_timestep_embedding=lowercase_  ,     time_embedding_type='''fourier'''  ,     mid_block_type='''UNetMidBlock1D'''  ,     down_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''')  ,     up_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''')  ,     )
     snake_case_ :     Dict				=	IPNDMScheduler()

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

 def 						_snake_case					(     self		:       Optional[int]  ,     lowercase_		:       Union[str, Any]  ,     lowercase_		:       Tuple=0				):
     if str(lowercase_				).startswith('''mps'''				):
         snake_case_ :     Any				=	torch.manual_seed(lowercase_				)
     else:
         snake_case_ :     Union[str, Any]				=	torch.Generator(device=lowercase_				).manual_seed(lowercase_				)
     snake_case_ :     str				=	{
         '''batch_size''': 1,
         '''generator''': generator,
         '''num_inference_steps''': 4,
     }
     return inputs

 def 						_snake_case					(     self		:       Dict				):
     snake_case_ :     Optional[Any]				=	'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     snake_case_ :     Tuple				=	self.get_dummy_components()
     snake_case_ :     int				=	DanceDiffusionPipeline(**lowercase_				)
     snake_case_ :     int				=	pipe.to(lowercase_				)
     pipe.set_progress_bar_config(disable=lowercase_				)

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

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

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

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

 @skip_mps
 def 						_snake_case					(     self		:       Any				):
     return super().test_save_load_optional_components()

 @skip_mps
 def 						_snake_case					(     self		:       Tuple				):
     return super().test_attention_slicing_forward_pass()






 def 						_snake_case					(     self		:       Union[str, Any]				):
     super().test_inference_batch_single_identical(expected_max_diff=3E-3				)





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

 def 						_snake_case					(     self		:       List[Any]				):
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

 def 						_snake_case					(     self		:       Tuple				):
     snake_case_ :     str				=	torch_device

     snake_case_ :     int				=	DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''				)
     snake_case_ :     str				=	pipe.to(lowercase_				)
     pipe.set_progress_bar_config(disable=lowercase_				)

     snake_case_ :     Optional[Any]				=	torch.manual_seed(0				)
     snake_case_ :     Any				=	pipe(generator=lowercase_  ,     num_inference_steps=100  ,     audio_length_in_s=4.0_96				)
     snake_case_ :     Tuple				=	output.audios

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

     assert audio.shape == (1, 2, pipe.unet.sample_size)
     snake_case_ :     Optional[Any]				=	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		:       Union[str, Any]				):
     snake_case_ :     Union[str, Any]				=	torch_device

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

     snake_case_ :     Dict				=	torch.manual_seed(0				)
     snake_case_ :     Tuple				=	pipe(generator=lowercase_  ,     num_inference_steps=100  ,     audio_length_in_s=4.0_96				)
     snake_case_ :     List[Any]				=	output.audios

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

     assert audio.shape == (1, 2, pipe.unet.sample_size)
     snake_case_ :     Optional[Any]				=	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 typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowercase__    :  List[Any]							    =	{
    '''configuration_distilbert''': [
        '''DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''DistilBertConfig''',
        '''DistilBertOnnxConfig''',
    ],
    '''tokenization_distilbert''': ['''DistilBertTokenizer'''],
}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowercase__    :  Any							    =	['''DistilBertTokenizerFast''']

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowercase__    :  int							    =	[
         '''DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''DistilBertForMaskedLM''',
         '''DistilBertForMultipleChoice''',
         '''DistilBertForQuestionAnswering''',
         '''DistilBertForSequenceClassification''',
         '''DistilBertForTokenClassification''',
         '''DistilBertModel''',
         '''DistilBertPreTrainedModel''',
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowercase__    :  Dict							    =	[
         '''TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''TFDistilBertForMaskedLM''',
         '''TFDistilBertForMultipleChoice''',
         '''TFDistilBertForQuestionAnswering''',
         '''TFDistilBertForSequenceClassification''',
         '''TFDistilBertForTokenClassification''',
         '''TFDistilBertMainLayer''',
         '''TFDistilBertModel''',
         '''TFDistilBertPreTrainedModel''',
     ]

try:
     if not is_flax_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowercase__    :  Tuple							    =	[
         '''FlaxDistilBertForMaskedLM''',
         '''FlaxDistilBertForMultipleChoice''',
         '''FlaxDistilBertForQuestionAnswering''',
         '''FlaxDistilBertForSequenceClassification''',
         '''FlaxDistilBertForTokenClassification''',
         '''FlaxDistilBertModel''',
         '''FlaxDistilBertPreTrainedModel''',
     ]


if TYPE_CHECKING:
     from .configuration_distilbert import (
         DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
         DistilBertConfig,
         DistilBertOnnxConfig,
     )
     from .tokenization_distilbert import DistilBertTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_distilbert_fast import DistilBertTokenizerFast

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_distilbert import (
              DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
              DistilBertForMaskedLM,
              DistilBertForMultipleChoice,
              DistilBertForQuestionAnswering,
              DistilBertForSequenceClassification,
              DistilBertForTokenClassification,
              DistilBertModel,
              DistilBertPreTrainedModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_distilbert import (
              TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFDistilBertForMaskedLM,
              TFDistilBertForMultipleChoice,
              TFDistilBertForQuestionAnswering,
              TFDistilBertForSequenceClassification,
              TFDistilBertForTokenClassification,
              TFDistilBertMainLayer,
              TFDistilBertModel,
              TFDistilBertPreTrainedModel,
          )

     try:
          if not is_flax_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_flax_distilbert import (
              FlaxDistilBertForMaskedLM,
              FlaxDistilBertForMultipleChoice,
              FlaxDistilBertForQuestionAnswering,
              FlaxDistilBertForSequenceClassification,
              FlaxDistilBertForTokenClassification,
              FlaxDistilBertModel,
              FlaxDistilBertPreTrainedModel,
          )

else:
     import sys

     lowercase__    :  Union[str, Any]							    =	_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





