
'''simple docstring'''







import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class UpperCAmelCase__      (					lowercase__       ,							unittest.TestCase      ):





  """simple docstring"""

  __UpperCAmelCase							:							Union[str, Any]    					=   AudioLDMPipeline
  __UpperCAmelCase							:							Optional[int]    					=   TEXT_TO_AUDIO_PARAMS
  __UpperCAmelCase							:							List[str]    					=   TEXT_TO_AUDIO_BATCH_PARAMS
  __UpperCAmelCase							:							List[str]    					=   frozenset(
      [
          '''num_inference_steps''',
          '''num_waveforms_per_prompt''',
          '''generator''',
          '''latents''',
          '''output_type''',
          '''return_dict''',
          '''callback''',
          '''callback_steps''',
      ]      )


  def     __lowercase						(						self :	Any			):


     '''simple docstring'''






     torch.manual_seed(0			)
     _a							:      Union[str, Any]     =  UNetaDConditionModel(
         block_out_channels=(32, 64)				,layers_per_block=2				,sample_size=32				,in_channels=4				,out_channels=4				,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')				,cross_attention_dim=(32, 64)				,class_embed_type='simple_projection'				,projection_class_embeddings_input_dim=32				,class_embeddings_concat=UpperCamelCase_				,)
     _a							:      Union[str, Any]     =  DDIMScheduler(
         beta_start=0.0_0085				,beta_end=0.012				,beta_schedule='scaled_linear'				,clip_sample=UpperCamelCase_				,set_alpha_to_one=UpperCamelCase_				,)
     torch.manual_seed(0			)
     _a							:      List[str]     =  AutoencoderKL(
         block_out_channels=[32, 64]				,in_channels=1				,out_channels=1				,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']				,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']				,latent_channels=4				,)
     torch.manual_seed(0			)
     _a							:      Optional[Any]     =  ClapTextConfig(
         bos_token_id=0				,eos_token_id=2				,hidden_size=32				,intermediate_size=37				,layer_norm_eps=1E-05				,num_attention_heads=4				,num_hidden_layers=5				,pad_token_id=1				,vocab_size=1000				,projection_dim=32				,)
     _a							:      Any     =  ClapTextModelWithProjection(UpperCamelCase_			)
     _a							:      List[Any]     =  RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta'				,model_max_length=77			)

     _a							:      Any     =  SpeechTaHifiGanConfig(
         model_in_dim=8				,sampling_rate=1_6000				,upsample_initial_channel=16				,upsample_rates=[2, 2]				,upsample_kernel_sizes=[4, 4]				,resblock_kernel_sizes=[3, 7]				,resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]]				,normalize_before=UpperCamelCase_				,)

     _a							:      Dict     =  SpeechTaHifiGan(UpperCamelCase_			)

     _a							:      List[str]     =  {
         'unet': unet,
         'scheduler': scheduler,
         'vae': vae,
         'text_encoder': text_encoder,
         'tokenizer': tokenizer,
         'vocoder': vocoder,
     }
     return components


  def     __lowercase						(						self :	str				,_a :	List[str]				,_a :	Union[str, Any]=0			):


     '''simple docstring'''






     if str(UpperCamelCase_			).startswith('mps'			):
        _a							:      Dict     =  torch.manual_seed(UpperCamelCase_			)
     else:
        _a							:      Union[str, Any]     =  torch.Generator(device=UpperCamelCase_			).manual_seed(UpperCamelCase_			)
     _a							:      List[str]     =  {
         'prompt': 'A hammer hitting a wooden surface',
         'generator': generator,
         'num_inference_steps': 2,
         'guidance_scale': 6.0,
     }
     return inputs


  def     __lowercase						(						self :	Dict			):


     '''simple docstring'''






     _a							:      Any     =  'cpu'  # ensure determinism for the device-dependent torch.Generator

     _a							:      Optional[Any]     =  self.get_dummy_components()
     _a							:      Optional[int]     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      List[str]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Optional[Any]     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      int     =  audioldm_pipe(**UpperCamelCase_			)
     _a							:      int     =  output.audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) == 256

     _a							:      List[str]     =  audio[:10]
     _a							:      List[str]     =  np.array(
         [-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033]			)

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


  def     __lowercase						(						self :	int			):


     '''simple docstring'''






     _a							:      str     =  self.get_dummy_components()
     _a							:      List[str]     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Any     =  audioldm_pipe.to(UpperCamelCase_			)
     _a							:      List[Any]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Any     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      List[str]     =  3 * [inputs['prompt']]

     # forward
     _a							:      str     =  audioldm_pipe(**UpperCamelCase_			)
     _a							:      str     =  output.audios[0]

     _a							:      List[Any]     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      List[str]     =  3 * [inputs.pop('prompt'			)]

     _a							:      Union[str, Any]     =  audioldm_pipe.tokenizer(
         UpperCamelCase_				,padding='max_length'				,max_length=audioldm_pipe.tokenizer.model_max_length				,truncation=UpperCamelCase_				,return_tensors='pt'				,)
     _a							:      Optional[int]     =  text_inputs['input_ids'].to(UpperCamelCase_			)

     _a							:      List[str]     =  audioldm_pipe.text_encoder(
         UpperCamelCase_				,)
     _a							:      List[str]     =  prompt_embeds.text_embeds
     # additional L_2 normalization over each hidden-state
     _a							:      Dict     =  F.normalize(UpperCamelCase_				,dim=-1			)

     _a							:      str     =  prompt_embeds

     # forward
     _a							:      Dict     =  audioldm_pipe(**UpperCamelCase_			)
     _a							:      str     =  output.audios[0]

     assert np.abs(audio_a - audio_a			).max() < 1E-2


  def     __lowercase						(						self :	Union[str, Any]			):


     '''simple docstring'''






     _a							:      Dict     =  self.get_dummy_components()
     _a							:      int     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Optional[int]     =  audioldm_pipe.to(UpperCamelCase_			)
     _a							:      str     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Tuple     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      Optional[Any]     =  3 * ['this is a negative prompt']
     _a							:      Any     =  negative_prompt
     _a							:      Any     =  3 * [inputs['prompt']]

     # forward
     _a							:      Optional[int]     =  audioldm_pipe(**UpperCamelCase_			)
     _a							:      int     =  output.audios[0]

     _a							:      str     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      Optional[int]     =  3 * [inputs.pop('prompt'			)]

     _a							:      str     =  []
     for p in [prompt, negative_prompt]:
        _a							:      Optional[int]     =  audioldm_pipe.tokenizer(
            UpperCamelCase_				,padding='max_length'				,max_length=audioldm_pipe.tokenizer.model_max_length				,truncation=UpperCamelCase_				,return_tensors='pt'				,)
        _a							:      Dict     =  text_inputs['input_ids'].to(UpperCamelCase_			)

        _a							:      Dict     =  audioldm_pipe.text_encoder(
            UpperCamelCase_				,)
        _a							:      Optional[int]     =  text_embeds.text_embeds
        # additional L_2 normalization over each hidden-state
        _a							:      Any     =  F.normalize(UpperCamelCase_				,dim=-1			)

        embeds.append(UpperCamelCase_			)

     _a							:      List[str]     =  embeds

     # forward
     _a							:      List[Any]     =  audioldm_pipe(**UpperCamelCase_			)
     _a							:      int     =  output.audios[0]

     assert np.abs(audio_a - audio_a			).max() < 1E-2


  def     __lowercase						(						self :	Optional[int]			):


     '''simple docstring'''






     _a							:      List[str]     =  'cpu'  # ensure determinism for the device-dependent torch.Generator
     _a							:      str     =  self.get_dummy_components()
     _a							:      int     =  PNDMScheduler(skip_prk_steps=UpperCamelCase_			)
     _a							:      Optional[Any]     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Union[str, Any]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      str     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      str     =  'egg cracking'
     _a							:      List[str]     =  audioldm_pipe(**UpperCamelCase_				,negative_prompt=UpperCamelCase_			)
     _a							:      List[str]     =  output.audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) == 256

     _a							:      List[Any]     =  audio[:10]
     _a							:      List[Any]     =  np.array(
         [-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032]			)

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


  def     __lowercase						(						self :	str			):


     '''simple docstring'''






     _a							:      Union[str, Any]     =  'cpu'  # ensure determinism for the device-dependent torch.Generator
     _a							:      Tuple     =  self.get_dummy_components()
     _a							:      Tuple     =  PNDMScheduler(skip_prk_steps=UpperCamelCase_			)
     _a							:      Any     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Tuple     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Dict     =  'A hammer hitting a wooden surface'

     # test num_waveforms_per_prompt=1 (default)
     _a							:      Optional[Any]     =  audioldm_pipe(UpperCamelCase_				,num_inference_steps=2			).audios

     assert audios.shape == (1, 256)

     # test num_waveforms_per_prompt=1 (default) for batch of prompts
     _a							:      Dict     =  2
     _a							:      Optional[int]     =  audioldm_pipe([prompt] * batch_size				,num_inference_steps=2			).audios

     assert audios.shape == (batch_size, 256)

     # test num_waveforms_per_prompt for single prompt
     _a							:      Tuple     =  2
     _a							:      Dict     =  audioldm_pipe(UpperCamelCase_				,num_inference_steps=2				,num_waveforms_per_prompt=UpperCamelCase_			).audios

     assert audios.shape == (num_waveforms_per_prompt, 256)

     # test num_waveforms_per_prompt for batch of prompts
     _a							:      List[Any]     =  2
     _a							:      Dict     =  audioldm_pipe(
         [prompt] * batch_size				,num_inference_steps=2				,num_waveforms_per_prompt=UpperCamelCase_			).audios

     assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)


  def     __lowercase						(						self :	Any			):


     '''simple docstring'''






     _a							:      Optional[Any]     =  'cpu'  # ensure determinism for the device-dependent torch.Generator
     _a							:      Union[str, Any]     =  self.get_dummy_components()
     _a							:      Any     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Union[str, Any]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)
     _a							:      int     =  audioldm_pipe.vocoder.config.sampling_rate

     _a							:      List[Any]     =  self.get_dummy_inputs(UpperCamelCase_			)
     _a							:      Optional[Any]     =  audioldm_pipe(audio_length_in_s=0.016				,**UpperCamelCase_			)
     _a							:      Optional[int]     =  output.audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) / vocoder_sampling_rate == 0.016

     _a							:      int     =  audioldm_pipe(audio_length_in_s=0.032				,**UpperCamelCase_			)
     _a							:      List[str]     =  output.audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) / vocoder_sampling_rate == 0.032


  def     __lowercase						(						self :	List[Any]			):


     '''simple docstring'''






     _a							:      Optional[Any]     =  self.get_dummy_components()
     _a							:      Optional[Any]     =  AudioLDMPipeline(**UpperCamelCase_			)
     _a							:      Optional[int]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Optional[Any]     =  ['hey']

     _a							:      Union[str, Any]     =  audioldm_pipe(UpperCamelCase_				,num_inference_steps=1			)
     _a							:      Union[str, Any]     =  output.audios.shape
     assert audio_shape == (1, 256)

     _a							:      str     =  audioldm_pipe.vocoder.config
     config.model_in_dim *= 2
     _a							:      str     =  SpeechTaHifiGan(UpperCamelCase_			).to(UpperCamelCase_			)
     _a							:      List[Any]     =  audioldm_pipe(UpperCamelCase_				,num_inference_steps=1			)
     _a							:      Optional[Any]     =  output.audios.shape
     # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
     assert audio_shape == (1, 256)


  def     __lowercase						(						self :	str			):


     '''simple docstring'''






     self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCamelCase_			)


  def     __lowercase						(						self :	Union[str, Any]			):


     '''simple docstring'''






     self._test_inference_batch_single_identical(test_mean_pixel_difference=UpperCamelCase_			)


  @unittest.skipIf(
      torch_device != 'cuda' or not is_xformers_available()				,reason='XFormers attention is only available with CUDA and `xformers` installed'				,)
  def     __lowercase						(						self :	Union[str, Any]			):


     '''simple docstring'''






     self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCamelCase_			)







@slow
class UpperCAmelCase__      (					unittest.TestCase      ):





  """simple docstring"""

  def     __lowercase						(						self :	Any			):


     '''simple docstring'''






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


  def     __lowercase						(						self :	str				,_a :	int				,_a :	Any="cpu"				,_a :	str=torch.floataa				,_a :	List[Any]=0			):


     '''simple docstring'''






     _a							:      int     =  torch.Generator(device=UpperCamelCase_			).manual_seed(UpperCamelCase_			)
     _a							:      Optional[int]     =  np.random.RandomState(UpperCamelCase_			).standard_normal((1, 8, 128, 16)			)
     _a							:      Union[str, Any]     =  torch.from_numpy(UpperCamelCase_			).to(device=UpperCamelCase_				,dtype=UpperCamelCase_			)
     _a							:      List[Any]     =  {
         'prompt': 'A hammer hitting a wooden surface',
         'latents': latents,
         'generator': generator,
         'num_inference_steps': 3,
         'guidance_scale': 2.5,
     }
     return inputs


  def     __lowercase						(						self :	Any			):


     '''simple docstring'''






     _a							:      List[str]     =  AudioLDMPipeline.from_pretrained('cvssp/audioldm'			)
     _a							:      int     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Tuple     =  self.get_inputs(UpperCamelCase_			)
     _a							:      str     =  25
     _a							:      int     =  audioldm_pipe(**UpperCamelCase_			).audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) == 8_1920

     _a							:      Optional[Any]     =  audio[7_7230:7_7240]
     _a							:      Union[str, Any]     =  np.array(
         [-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315]			)
     _a							:      Tuple     =  np.abs(expected_slice - audio_slice			).max()
     assert max_diff < 1E-2


  def     __lowercase						(						self :	Optional[int]			):


     '''simple docstring'''






     _a							:      Any     =  AudioLDMPipeline.from_pretrained('cvssp/audioldm'			)
     _a							:      List[Any]     =  LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config			)
     _a							:      List[Any]     =  audioldm_pipe.to(UpperCamelCase_			)
     audioldm_pipe.set_progress_bar_config(disable=UpperCamelCase_			)

     _a							:      Any     =  self.get_inputs(UpperCamelCase_			)
     _a							:      Dict     =  audioldm_pipe(**UpperCamelCase_			).audios[0]

     assert audio.ndim == 1
     assert len(UpperCamelCase_			) == 8_1920

     _a							:      Optional[int]     =  audio[2_7780:2_7790]
     _a							:      Optional[Any]     =  np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212]			)
     _a							:      Tuple     =  np.abs(expected_slice - audio_slice			).max()
     assert max_diff < 3E-2





"""simple docstring"""



from ...configuration_utils import PretrainedConfig





class 				a			(					lowercase      ):
      UpperCamelCase							:   Union[str, Any]           =     """bert-generation"""



      def __init__(   self     ,	UpperCamelCase_=50_358     ,	UpperCamelCase_=1_024     ,	UpperCamelCase_=24     ,	UpperCamelCase_=16     ,	UpperCamelCase_=4_096     ,	UpperCamelCase_="gelu"     ,	UpperCamelCase_=0.1     ,	UpperCamelCase_=0.1     ,	UpperCamelCase_=512     ,	UpperCamelCase_=0.02     ,	UpperCamelCase_=1E-12     ,	UpperCamelCase_=0     ,	UpperCamelCase_=2     ,	UpperCamelCase_=1     ,	UpperCamelCase_="absolute"     ,	UpperCamelCase_=True     ,	**UpperCamelCase_     ,	):
          super().__init__(pad_token_id=UpperCamelCase_     ,	bos_token_id=UpperCamelCase_     ,	eos_token_id=UpperCamelCase_     ,	**UpperCamelCase_      )

          UpperCAmelCase__	:      Optional[Any]     							=					vocab_size
          UpperCAmelCase__	:      Union[str, Any]     							=					hidden_size
          UpperCAmelCase__	:      Optional[Any]     							=					num_hidden_layers
          UpperCAmelCase__	:      Dict     							=					num_attention_heads
          UpperCAmelCase__	:      Dict     							=					hidden_act
          UpperCAmelCase__	:      Optional[Any]     							=					intermediate_size
          UpperCAmelCase__	:      Optional[int]     							=					hidden_dropout_prob
          UpperCAmelCase__	:      Tuple     							=					attention_probs_dropout_prob
          UpperCAmelCase__	:      List[Any]     							=					max_position_embeddings
          UpperCAmelCase__	:      Optional[int]     							=					initializer_range
          UpperCAmelCase__	:      Optional[int]     							=					layer_norm_eps
          UpperCAmelCase__	:      Union[str, Any]     							=					position_embedding_type
          UpperCAmelCase__	:      Dict     							=					use_cache

