import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
     import torch_xla.core.xla_model as xm






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: int ,	lowerCAmelCase_: bool = False     ):
      if device_specific:
            seed += AcceleratorState().process_index
      random.seed(lowerCAmelCase_     )
      np.random.seed(lowerCAmelCase_     )
      torch.manual_seed(lowerCAmelCase_     )
      if is_xpu_available():
            torch.xpu.manual_seed_all(lowerCAmelCase_     )
      elif is_npu_available():
            torch.npu.manual_seed_all(lowerCAmelCase_     )
      else:
            torch.cuda.manual_seed_all(lowerCAmelCase_     )
      # ^^ safe to call this function even if cuda is not available
      if is_tpu_available():
            xm.set_rng_state(lowerCAmelCase_     )






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: Optional[RNGType] = None ,	lowerCAmelCase_: Optional[torch.Generator] = None     ):
      # Get the proper rng state
      if rng_type == RNGType.TORCH:
            snake_case_     :			List[Any]       =       torch.get_rng_state()
      elif rng_type == RNGType.CUDA:
            snake_case_     :			Dict       =       torch.cuda.get_rng_state()
      elif rng_type == RNGType.XLA:
            assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
            snake_case_     :			Tuple       =       torch.tensor(xm.get_rng_state()     )
      elif rng_type == RNGType.NPU:
            assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
            snake_case_     :			List[str]       =       torch.npu.get_rng_state()
      elif rng_type == RNGType.XPU:
            assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
            snake_case_     :			List[str]       =       torch.xpu.get_rng_state()
      elif rng_type == RNGType.GENERATOR:
            assert generator is not None, "Need a generator to synchronize its seed."
            snake_case_     :			Optional[Any]       =       generator.get_state()

      # Broadcast the rng state from device 0 to other devices
      snake_case_     :			List[Any]       =       AcceleratorState()
      if state.distributed_type == DistributedType.TPU:
            snake_case_     :			int       =       rng_state.to(xm.xla_device()     )
            xm.collective_broadcast([rng_state]     )
            xm.mark_step()
            snake_case_     :			List[str]       =       rng_state.cpu()
      elif (
          state.distributed_type in CUDA_DISTRIBUTED_TYPES
          or state.distributed_type == DistributedType.MULTI_NPU
          or state.distributed_type == DistributedType.MULTI_XPU
      ):
            snake_case_     :			Dict       =       rng_state.to(state.device     )
            torch.distributed.broadcast(lowerCAmelCase_ ,	0     )
            snake_case_     :			Dict       =       rng_state.cpu()
      elif state.distributed_type == DistributedType.MULTI_CPU:
            torch.distributed.broadcast(lowerCAmelCase_ ,	0     )

      # Set the broadcast rng state
      if rng_type == RNGType.TORCH:
            torch.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.CUDA:
            torch.cuda.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.NPU:
            torch.npu.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.XPU:
            torch.xpu.set_rng_state(lowerCAmelCase_     )
      elif rng_type == RNGType.XLA:
            xm.set_rng_state(rng_state.item()     )
      elif rng_type == RNGType.GENERATOR:
            generator.set_state(lowerCAmelCase_     )






def 					SCREAMING_SNAKE_CASE_			(		lowerCAmelCase_: List[Union[str, RNGType]] ,	lowerCAmelCase_: Optional[torch.Generator] = None     ):
      for rng_type in rng_types:
            synchronize_rng_state(RNGType(lowerCAmelCase_     ) ,	generator=lowerCAmelCase_     )




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()


UpperCAmelCase							=       "./tests/fixtures/elise_format0.mid"



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



   def 					UpperCAmelCase__       (				self   :   Tuple   )							->     Optional[Any]:




         '''simple docstring'''




         torch.manual_seed(0   )
         snake_case_     :			List[Any]       =       SpectrogramNotesEncoder(
             max_length=20_48			,	vocab_size=15_36			,	d_model=7_68			,	dropout_rate=0.1			,	num_layers=1			,	num_heads=1			,	d_kv=4			,	d_ff=20_48			,	feed_forward_proj="gated-gelu"			,	)

         snake_case_     :			int       =       SpectrogramContEncoder(
             input_dims=1_28			,	targets_context_length=2_56			,	d_model=7_68			,	dropout_rate=0.1			,	num_layers=1			,	num_heads=1			,	d_kv=4			,	d_ff=20_48			,	feed_forward_proj="gated-gelu"			,	)

         snake_case_     :			Any       =       TaFilmDecoder(
             input_dims=1_28			,	targets_length=2_56			,	max_decoder_noise_time=2_0000.0			,	d_model=7_68			,	num_layers=1			,	num_heads=1			,	d_kv=4			,	d_ff=20_48			,	dropout_rate=0.1			,	)

         snake_case_     :			List[Any]       =       DDPMScheduler()

         snake_case_     :			List[Any]       =       {
             "notes_encoder": notes_encoder.eval(),
             "continuous_encoder": continuous_encoder.eval(),
             "decoder": decoder.eval(),
             "scheduler": scheduler,
             "melgan": None,
         }
         return components



   def 					UpperCAmelCase__       (				self   :   Dict			,	A__   :   int			,	A__   :   Dict=0   )							->     Tuple:




         '''simple docstring'''




         if str(A__   ).startswith("mps"   ):
               snake_case_     :			List[Any]       =       torch.manual_seed(A__   )
         else:
               snake_case_     :			List[Any]       =       torch.Generator(device=A__   ).manual_seed(A__   )
         snake_case_     :			Optional[int]       =       {
             "input_tokens": [
                 [11_34, 90, 11_35, 11_33, 10_80, 1_12, 11_32, 10_80, 11_33, 10_79, 1_33, 11_32, 10_79, 11_33, 1] + [0] * 20_33
             ],
             "generator": generator,
             "num_inference_steps": 4,
             "output_type": "mel",
         }
         return inputs



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




         '''simple docstring'''




         snake_case_     :			List[Any]       =       "cpu"  # ensure determinism for the device-dependent torch.Generator
         snake_case_     :			List[Any]       =       self.get_dummy_components()
         snake_case_     :			str       =       SpectrogramDiffusionPipeline(**A__   )
         snake_case_     :			Optional[int]       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )

         snake_case_     :			List[Any]       =       self.get_dummy_inputs(A__   )
         snake_case_     :			Union[str, Any]       =       pipe(**A__   )
         snake_case_     :			str       =       output.audios

         snake_case_     :			List[Any]       =       mel[0, -3:, -3:]

         assert mel_slice.shape == (3, 3)
         snake_case_     :			Any       =       np.array(
             [-11.51_2925, -4.78_8215, -0.4617_2905, -2.05_1715, -10.53_9147, -10.97_0963, -9.09_1634, 4.0, 4.0]   )
         assert np.abs(mel_slice.flatten() - expected_slice   ).max() < 1E-2



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   Any   )							->     Tuple:




         '''simple docstring'''




         return super().test_save_load_local()



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   Union[str, Any]   )							->     List[Any]:




         '''simple docstring'''




         return super().test_dict_tuple_outputs_equivalent()



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




         '''simple docstring'''




         return super().test_save_load_optional_components()



   @skip_mps
   def 					UpperCAmelCase__       (				self   :   Optional[int]   )							->     List[str]:




         '''simple docstring'''




         return super().test_attention_slicing_forward_pass()



   def 					UpperCAmelCase__       (				self   :   List[str]   )							->     List[Any]:




         '''simple docstring'''




         pass



   def 					UpperCAmelCase__       (				self   :   Dict   )							->     str:




         '''simple docstring'''




         pass



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




         '''simple docstring'''




         return super().test_progress_bar()



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



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




         '''simple docstring'''




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



   def 					UpperCAmelCase__       (				self   :   int   )							->     Dict:




         '''simple docstring'''




         snake_case_     :			Optional[int]       =       torch_device

         snake_case_     :			List[str]       =       SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"   )
         snake_case_     :			Dict       =       pipe.melgan
         snake_case_     :			Optional[Any]       =       None

         snake_case_     :			int       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )

         def callback(A__   :   Dict			,	A__   :   Optional[Any]   ):
               # decode mel to audio
               snake_case_     :			str       =       melgan(input_features=mel_output.astype(np.floataa   )   )[0]
               assert len(audio[0]   ) == 8_19_20 * (step + 1)
               # simulate that audio is played
               return audio

         snake_case_     :			List[str]       =       MidiProcessor()
         snake_case_     :			Dict       =       processor(A__   )

         snake_case_     :			Optional[Any]       =       input_tokens[:3]
         snake_case_     :			Dict       =       torch.manual_seed(0   )
         pipe(A__			,	num_inference_steps=5			,	generator=A__			,	callback=A__			,	output_type="mel"   )



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




         '''simple docstring'''




         snake_case_     :			Any       =       torch_device

         snake_case_     :			List[Any]       =       SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"   )
         snake_case_     :			Any       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )
         snake_case_     :			Any       =       MidiProcessor()

         snake_case_     :			List[Any]       =       processor(A__   )
         # just run two denoising loops
         snake_case_     :			str       =       input_tokens[:2]

         snake_case_     :			Tuple       =       torch.manual_seed(0   )
         snake_case_     :			int       =       pipe(A__			,	num_inference_steps=2			,	generator=A__   )

         snake_case_     :			int       =       output.audios[0]

         assert abs(np.abs(A__   ).sum() - 3612.841   ) < 1E-1



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




         '''simple docstring'''




         snake_case_     :			Union[str, Any]       =       torch_device

         snake_case_     :			Union[str, Any]       =       SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion"   )
         snake_case_     :			Tuple       =       pipe.to(A__   )
         pipe.set_progress_bar_config(disable=A__   )

         snake_case_     :			int       =       MidiProcessor()

         snake_case_     :			int       =       processor(A__   )

         # just run 4 denoising loops
         snake_case_     :			Union[str, Any]       =       input_tokens[:4]

         snake_case_     :			Optional[Any]       =       torch.manual_seed(0   )
         snake_case_     :			Optional[Any]       =       pipe(A__			,	num_inference_steps=1_00			,	generator=A__   )

         snake_case_     :			List[str]       =       output.audios[0]
         assert abs(np.abs(A__   ).sum() - 9389.1111   ) < 5E-2



