




'''simple docstring'''
import unittest

import numpy as np

from transformers import is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
  import tensorflow as tf

  from transformers.activations_tf import get_tf_activation






@require_tf
class 			SCREAMING_SNAKE_CASE(							unittest.TestCase	):

       def        snake_case__     (       self	)       ->   Optional[int]:

           """simple docstring"""



           __lowercase     							=		tf.constant([-100, -1.0, -0.1, 0, 0.1, 1.0, 1_00.0]	)
           __lowercase     							=		get_tf_activation("""gelu"""	)
           __lowercase     							=		get_tf_activation("""gelu_10"""	)

           __lowercase     							=		gelu(lowerCamelCase__	)
           __lowercase     							=		geluaa(lowerCamelCase__	)

           __lowercase     							=		tf.where(y_gelu_aa < 10.0   ,						1.0   ,						0.0	)

           self.assertEqual(tf.math.reduce_max(lowerCamelCase__	).numpy().item()   ,						10.0	)
           self.assertTrue(np.allclose(y_gelu * clipped_mask   ,						y_gelu_aa * clipped_mask	)	)




       def        snake_case__     (       self	)       ->   Tuple:

           """simple docstring"""



           get_tf_activation("""gelu"""	)
           get_tf_activation("""gelu_10"""	)
           get_tf_activation("""gelu_fast"""	)
           get_tf_activation("""gelu_new"""	)
           get_tf_activation("""glu"""	)
           get_tf_activation("""mish"""	)
           get_tf_activation("""quick_gelu"""	)
           get_tf_activation("""relu"""	)
           get_tf_activation("""sigmoid"""	)
           get_tf_activation("""silu"""	)
           get_tf_activation("""swish"""	)
           get_tf_activation("""tanh"""	)
           with self.assertRaises(lowerCamelCase__	):
               get_tf_activation("""bogus"""	)
           with self.assertRaises(lowerCamelCase__	):
               get_tf_activation(lowerCamelCase__	)










'''simple docstring'''
import gc
import unittest

import numpy as np
import torch

from diffusers import DDPMScheduler, MidiProcessor, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
from diffusers.utils import require_torch_gpu, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_note_seq, require_onnxruntime

from ..pipeline_params import TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS, TOKENS_TO_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


A				: List[str]					      =			"""./tests/fixtures/elise_format0.mid"""






@unittest.skip("""The note-seq package currently throws an error on import"""	)
class 			SCREAMING_SNAKE_CASE(							__A  , unittest.TestCase	):
       snake_case_					:	List[str]       =   SpectrogramDiffusionPipeline
       snake_case_					:	Any       =   PipelineTesterMixin.required_optional_params - {
           """callback""",
           """latents""",
           """callback_steps""",
           """output_type""",
           """num_images_per_prompt""",
       }
       snake_case_					:	int       =   False
       snake_case_					:	Tuple       =   False
       snake_case_					:	Tuple       =   TOKENS_TO_AUDIO_GENERATION_PARAMS
       snake_case_					:	Optional[int]       =   TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS

       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           torch.manual_seed(0	)
           __lowercase     							=		SpectrogramNotesEncoder(
               max_length=2048   ,						vocab_size=1536   ,						d_model=768   ,						dropout_rate=0.1   ,						num_layers=1   ,						num_heads=1   ,						d_kv=4   ,						d_ff=2048   ,						feed_forward_proj="""gated-gelu"""   ,						)

           __lowercase     							=		SpectrogramContEncoder(
               input_dims=128   ,						targets_context_length=256   ,						d_model=768   ,						dropout_rate=0.1   ,						num_layers=1   ,						num_heads=1   ,						d_kv=4   ,						d_ff=2048   ,						feed_forward_proj="""gated-gelu"""   ,						)

           __lowercase     							=		TaFilmDecoder(
               input_dims=128   ,						targets_length=256   ,						max_decoder_noise_time=2_00_00.0   ,						d_model=768   ,						num_layers=1   ,						num_heads=1   ,						d_kv=4   ,						d_ff=2048   ,						dropout_rate=0.1   ,						)

           __lowercase     							=		DDPMScheduler()

           __lowercase     							=		{
               """notes_encoder""": notes_encoder.eval(),
               """continuous_encoder""": continuous_encoder.eval(),
               """decoder""": decoder.eval(),
               """scheduler""": scheduler,
               """melgan""": None,
           }
           return components

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__=0	)       ->   Any:

           """simple docstring"""



           if str(lowerCamelCase__	).startswith("""mps"""	):
               __lowercase     							=		torch.manual_seed(lowerCamelCase__	)
           else:
               __lowercase     							=		torch.Generator(device=lowerCamelCase__	).manual_seed(lowerCamelCase__	)
           __lowercase     							=		{
               """input_tokens""": [
                   [1134, 90, 1135, 1133, 1080, 112, 1132, 1080, 1133, 1079, 133, 1132, 1079, 1133, 1] + [0] * 2033
               ],
               """generator""": generator,
               """num_inference_steps""": 4,
               """output_type""": """mel""",
           }
           return inputs

       def        snake_case__     (       self	)       ->   str:

           """simple docstring"""



           __lowercase     							=		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
           __lowercase     							=		self.get_dummy_components()
           __lowercase     							=		SpectrogramDiffusionPipeline(**lowerCamelCase__	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

           __lowercase     							=		self.get_dummy_inputs(lowerCamelCase__	)
           __lowercase     							=		pipe(**lowerCamelCase__	)
           __lowercase     							=		output.audios

           __lowercase     							=		mel[0, -3:, -3:]

           assert mel_slice.shape == (3, 3)
           __lowercase     							=		np.array(
               [-11.51_29_25, -4.78_82_15, -0.46_17_29_05, -2.05_17_15, -10.53_91_47, -10.97_09_63, -9.09_16_34, 4.0, 4.0]	)
           assert np.abs(mel_slice.flatten() - expected_slice	).max() < 1E-2

       @skip_mps
       def        snake_case__     (       self	)       ->   Any:

           """simple docstring"""



           return super().test_save_load_local()

       @skip_mps
       def        snake_case__     (       self	)       ->   Tuple:

           """simple docstring"""



           return super().test_dict_tuple_outputs_equivalent()

       @skip_mps
       def        snake_case__     (       self	)       ->   Any:

           """simple docstring"""



           return super().test_save_load_optional_components()

       @skip_mps
       def        snake_case__     (       self	)       ->   List[str]:

           """simple docstring"""



           return super().test_attention_slicing_forward_pass()

       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           pass

       def        snake_case__     (       self	)       ->   Union[str, Any]:

           """simple docstring"""



           pass




       @skip_mps
       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           return super().test_progress_bar()






@slow
@require_torch_gpu
@require_onnxruntime
@require_note_seq
class 			SCREAMING_SNAKE_CASE(							unittest.TestCase	):

       def        snake_case__     (       self	)       ->   Tuple:

           """simple docstring"""



           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()

       def        snake_case__     (       self	)       ->   List[Any]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.melgan
           __lowercase     							=		None

           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

           def callback(lowerCamelCase__   ,						lowerCamelCase__	):
               # decode mel to audio
               __lowercase     							=		melgan(input_features=mel_output.astype(np.floataa	)	)[0]
               assert len(audio[0]	) == 8_1920 * (step + 1)
               # simulate that audio is played
               return audio

           __lowercase     							=		MidiProcessor()
           __lowercase     							=		processor(lowerCamelCase__	)

           __lowercase     							=		input_tokens[:3]
           __lowercase     							=		torch.manual_seed(0	)
           pipe(lowerCamelCase__   ,						num_inference_steps=5   ,						generator=lowerCamelCase__   ,						callback=lowerCamelCase__   ,						output_type="""mel"""	)

       def        snake_case__     (       self	)       ->   Union[str, Any]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)
           __lowercase     							=		MidiProcessor()

           __lowercase     							=		processor(lowerCamelCase__	)
           # just run two denoising loops
           __lowercase     							=		input_tokens[:2]

           __lowercase     							=		torch.manual_seed(0	)
           __lowercase     							=		pipe(lowerCamelCase__   ,						num_inference_steps=2   ,						generator=lowerCamelCase__	)

           __lowercase     							=		output.audios[0]

           assert abs(np.abs(lowerCamelCase__	).sum() - 36_12.8_41	) < 1E-1




       def        snake_case__     (       self	)       ->   List[str]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

           __lowercase     							=		MidiProcessor()

           __lowercase     							=		processor(lowerCamelCase__	)

           # just run 4 denoising loops
           __lowercase     							=		input_tokens[:4]

           __lowercase     							=		torch.manual_seed(0	)
           __lowercase     							=		pipe(lowerCamelCase__   ,						num_inference_steps=100   ,						generator=lowerCamelCase__	)

           __lowercase     							=		output.audios[0]
           assert abs(np.abs(lowerCamelCase__	).sum() - 93_89.11_11	) < 5E-2




