






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


lowercase_								=	'./tests/fixtures/elise_format0.mid'


@unittest.skip("The note-seq package currently throws an error on import"		)
class    snake_case						(				_lowerCAmelCase  ,      unittest.TestCase		):


   '''simple docstring'''

   A_		:      Any							=					SpectrogramDiffusionPipeline
   A_		:      List[str]							=					PipelineTesterMixin.required_optional_params - {
       "callback",
       "latents",
       "callback_steps",
       "output_type",
       "num_images_per_prompt",
   }
   A_		:      Dict							=					False
   A_		:      Union[str, Any]							=					False
   A_		:      List[str]							=					TOKENS_TO_AUDIO_GENERATION_PARAMS
   A_		:      str							=					TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[Any]    ):

     '''simple docstring'''
     torch.manual_seed(0    )
     __A		     =					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''',			)

     __A		     =					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''',			)

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

     __A		     =					DDPMScheduler()

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


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple,			_lowerCamelCase					:	Optional[Any],			_lowerCamelCase					:	int=0    ):

     '''simple docstring'''
     if str(_lowerCamelCase    ).startswith('''mps'''    ):
       __A		     =					torch.manual_seed(_lowerCamelCase    )
     else:
       __A		     =					torch.Generator(device=_lowerCamelCase    ).manual_seed(_lowerCamelCase    )
     __A		     =					{
         '''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 							_SCREAMING_SNAKE_CASE							(      self					:	str    ):

     '''simple docstring'''
     __A		     =					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     __A		     =					self.get_dummy_components()
     __A		     =					SpectrogramDiffusionPipeline(**_lowerCamelCase    )
     __A		     =					pipe.to(_lowerCamelCase    )
     pipe.set_progress_bar_config(disable=_lowerCamelCase    )

     __A		     =					self.get_dummy_inputs(_lowerCamelCase    )
     __A		     =					pipe(**_lowerCamelCase    )
     __A		     =					output.audios

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

     assert mel_slice.shape == (3, 3)
     __A		     =					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 							_SCREAMING_SNAKE_CASE							(      self					:	List[str]    ):

     '''simple docstring'''
     return super().test_save_load_local()


   @skip_mps
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Dict    ):

     '''simple docstring'''
     return super().test_dict_tuple_outputs_equivalent()


   @skip_mps
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Union[str, Any]    ):

     '''simple docstring'''
     return super().test_save_load_optional_components()


   @skip_mps
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Union[str, Any]    ):

     '''simple docstring'''
     return super().test_attention_slicing_forward_pass()


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[Any]    ):

     '''simple docstring'''
     pass


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[Any]    ):

     '''simple docstring'''
     pass






   @skip_mps
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[int]    ):

     '''simple docstring'''
     return super().test_progress_bar()





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


   '''simple docstring'''

   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()


   def 							_SCREAMING_SNAKE_CASE							(      self					:	str    ):

     '''simple docstring'''
     # TODO - test that pipeline can decode tokens in a callback
     # so that music can be played live
     __A		     =					torch_device

     __A		     =					SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''    )
     __A		     =					pipe.melgan
     __A		     =					None

     __A		     =					pipe.to(_lowerCamelCase    )
     pipe.set_progress_bar_config(disable=_lowerCamelCase    )

     def callback(_lowerCamelCase					:	Tuple,			_lowerCamelCase					:	str    ):
       # decode mel to audio
       __A		     =					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

     __A		     =					MidiProcessor()
     __A		     =					processor(_lowerCamelCase    )

     __A		     =					input_tokens[:3]
     __A		     =					torch.manual_seed(0    )
     pipe(_lowerCamelCase,			num_inference_steps=5,			generator=_lowerCamelCase,			callback=_lowerCamelCase,			output_type='''mel'''    )


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

     '''simple docstring'''
     __A		     =					torch_device

     __A		     =					SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''    )
     __A		     =					pipe.to(_lowerCamelCase    )
     pipe.set_progress_bar_config(disable=_lowerCamelCase    )
     __A		     =					MidiProcessor()

     __A		     =					processor(_lowerCamelCase    )
     # just run two denoising loops
     __A		     =					input_tokens[:2]

     __A		     =					torch.manual_seed(0    )
     __A		     =					pipe(_lowerCamelCase,			num_inference_steps=2,			generator=_lowerCamelCase    )

     __A		     =					output.audios[0]

     assert abs(np.abs(_lowerCamelCase    ).sum() - 36_12.8_41    ) < 1e-1






   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     __A		     =					torch_device

     __A		     =					SpectrogramDiffusionPipeline.from_pretrained('''google/music-spectrogram-diffusion'''    )
     __A		     =					pipe.to(_lowerCamelCase    )
     pipe.set_progress_bar_config(disable=_lowerCamelCase    )

     __A		     =					MidiProcessor()

     __A		     =					processor(_lowerCamelCase    )

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

     __A		     =					torch.manual_seed(0    )
     __A		     =					pipe(_lowerCamelCase,			num_inference_steps=1_00,			generator=_lowerCamelCase    )

     __A		     =					output.audios[0]
     assert abs(np.abs(_lowerCamelCase    ).sum() - 93_89.11_11    ) < 5e-2









import argparse
import os
import pathlib

import fairseq
import torch
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import (
    DataaVecTextConfig,
    DataaVecTextForMaskedLM,
    DataaVecTextForSequenceClassification,
    DataaVecTextModel,
)
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)

# IMPORTANT: In order for this script to run, please make sure to download the dictionary: `dict.txt` from wget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz
# File copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_text.py
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("""0.9.0"""):
	raise Exception("""requires fairseq >= 0.9.0""")


logging.set_verbosity_info()
UpperCAmelCase							=       logging.get_logger(__name__)

UpperCAmelCase							=       """Hello world! cécé herlolip"""

def       A_   (						__a  :					str			,		__a  :					str			,		__a  :					bool		):

				"""simple docstring"""
				a__   ,      a__					   =		os.path.split(__a		)
				a__					   =		DataaVecTextModel.from_pretrained(
				    __a			,		checkpoint_file=__a		)
				dataavec.eval()  # disable dropout
				a__					   =		dataavec.models[0]
				a__					   =		dataavec_model.encoder.sentence_encoder
				a__					   =		DataaVecTextConfig(
				    vocab_size=dataavec_sent_encoder.embed_tokens.num_embeddings			,		hidden_size=dataavec_model.args.encoder_embed_dim			,		num_hidden_layers=dataavec_model.args.encoder_layers			,		num_attention_heads=dataavec_model.args.encoder_attention_heads			,		intermediate_size=dataavec_model.args.encoder_ffn_embed_dim			,		max_position_embeddings=514			,		type_vocab_size=1			,		layer_norm_eps=1e-5			,		)
				if classification_head:
								a__					   =		dataavec.model.classification_heads["""mnli"""].out_proj.weight.shape[0]
				print("""Our BERT config:"""			,		__a		)

				a__					   =		DataaVecTextForSequenceClassification(__a		) if classification_head else DataaVecTextForMaskedLM(__a		)
				model.eval()

				# Now let's copy all the weights.
				# Embeddings
				a__					   =		dataavec_sent_encoder.embed_tokens.weight
				a__					   =		dataavec_sent_encoder.embed_positions.weight
				a__					   =		torch.zeros_like(
				    model.dataavec_text.embeddings.token_type_embeddings.weight		)  # just zero them out b/c data2vec doesn't use them.
				a__					   =		dataavec_sent_encoder.layernorm_embedding.weight
				a__					   =		dataavec_sent_encoder.layernorm_embedding.bias

				for i in range(config.num_hidden_layers		):
								# Encoder: start of layer
								a__					   =		model.dataavec_text.encoder.layer[i]
								a__					   =		dataavec_sent_encoder.layers[i]

								# self attention
								a__					   =		layer.attention.self
								assert dataavec_layer.self_attn.k_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)		), (
								    "Shape for data2vec_layer.self_attn.k_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)		)}'''
								)
								assert dataavec_layer.self_attn.q_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)		), (
								    "Shape for data2vec_layer.self_attn.q_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)		)}'''
								)
								assert dataavec_layer.self_attn.v_proj.weight.data.shape == torch.Size(
								    (config.hidden_size, config.hidden_size)		), (
								    "Shape for data2vec_layer.self_attn.v_proj.weight.data should be"
								    F''' {torch.Size((config.hidden_size, config.hidden_size)		)}'''
								)

								a__					   =		dataavec_layer.self_attn.q_proj.weight
								a__					   =		dataavec_layer.self_attn.q_proj.bias
								a__					   =		dataavec_layer.self_attn.k_proj.weight
								a__					   =		dataavec_layer.self_attn.k_proj.bias
								a__					   =		dataavec_layer.self_attn.v_proj.weight
								a__					   =		dataavec_layer.self_attn.v_proj.bias

								# self-attention output
								a__					   =		layer.attention.output
								assert (
								    self_output.dense.weight.shape == dataavec_layer.self_attn.out_proj.weight.shape
								), F'''Shape for self_output.dense.weight should be {dataavec_layer.self_attn.out_proj.weight.shape}'''
								a__					   =		dataavec_layer.self_attn.out_proj.weight
								a__					   =		dataavec_layer.self_attn.out_proj.bias
								a__					   =		dataavec_layer.self_attn_layer_norm.weight
								a__					   =		dataavec_layer.self_attn_layer_norm.bias

								# intermediate
								a__					   =		layer.intermediate
								assert (
								    intermediate.dense.weight.shape == dataavec_layer.fca.weight.shape
								), F'''Shape for intermediate.dense.weight should be {dataavec_layer.fca.weight.shape}'''
								a__					   =		dataavec_layer.fca.weight
								a__					   =		dataavec_layer.fca.bias

								# output
								a__					   =		layer.output
								assert (
								    bert_output.dense.weight.shape == dataavec_layer.fca.weight.shape
								), F'''Shape for bert_output.dense.weight should be {dataavec_layer.fca.weight.shape}'''
								a__					   =		dataavec_layer.fca.weight
								a__					   =		dataavec_layer.fca.bias
								a__					   =		dataavec_layer.final_layer_norm.weight
								a__					   =		dataavec_layer.final_layer_norm.bias
								# end of layer

				if classification_head:
								a__					   =		dataavec.model.classification_heads["""mnli"""].dense.weight
								a__					   =		dataavec.model.classification_heads["""mnli"""].dense.bias
								a__					   =		dataavec.model.classification_heads["""mnli"""].out_proj.weight
								a__					   =		dataavec.model.classification_heads["""mnli"""].out_proj.bias
				else:
								# LM Head
								a__					   =		dataavec_model.encoder.lm_head.dense.weight
								a__					   =		dataavec_model.encoder.lm_head.dense.bias
								a__					   =		dataavec_model.encoder.lm_head.layer_norm.weight
								a__					   =		dataavec_model.encoder.lm_head.layer_norm.bias
								a__					   =		dataavec_model.encoder.lm_head.weight
								a__					   =		dataavec_model.encoder.lm_head.bias

				# Let's check that we get the same results.
				a__					   =		dataavec.encode(__a		).unsqueeze(0		)  # batch of size 1

				a__					   =		model(__a		)[0]
				if classification_head:
								a__					   =		dataavec.model.classification_heads["""mnli"""](dataavec.extract_features(__a		)		)
				else:
								a__					   =		dataavec_model(__a		)[0]
				print(our_output.shape			,		their_output.shape		)
				a__					   =		torch.max(torch.abs(our_output - their_output		)		).item()
				print(F'''max_absolute_diff = {max_absolute_diff}'''		)  # ~ 1e-7
				a__					   =		torch.allclose(__a			,		__a			,		atol=1e-3		)
				print("""Do both models output the same tensors?"""			,		"""🔥""" if success else """💩"""		)
				if not success:
								raise Exception("""Something went wRoNg"""		)

				pathlib.Path(__a		).mkdir(parents=__a			,		exist_ok=__a		)
				print(F'''Saving model to {pytorch_dump_folder_path}'''		)
				model.save_pretrained(__a		)


if __name__ == "__main__":
	UpperCAmelCase							=       argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    """--checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
	)
	parser.add_argument(
	    """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
	)
	parser.add_argument(
	    """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head."""
	)
	UpperCAmelCase							=       parser.parse_args()
	convert_dataavec_checkpoint_to_pytorch(
	    args.checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
	)

