





from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand

def   a_   (			lowerCAmelCase_				:      Namespace     ):
   return ConvertCommand(
       args.model_type,     args.tf_checkpoint,     args.pytorch_dump_output,     args.config,     args.finetuning_task_name     )


_snake_case  :   Optional[int]						   =  '\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n'




class     _UpperCAmelCase   (   _UpperCamelCase   ):

  """simple docstring"""


  @staticmethod
  def     lowercase		(    lowerCAmelCase_			:		ArgumentParser					)							->						int:
     __lowerCAmelCase							     =     parser.add_parser(
         'convert' ,  help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' ,  )
     train_parser.add_argument('--model_type' ,  type=lowerCAmelCase_ ,  required=lowerCAmelCase_ ,  help='Model\'s type.'					)
     train_parser.add_argument(
         '--tf_checkpoint' ,  type=lowerCAmelCase_ ,  required=lowerCAmelCase_ ,  help='TensorFlow checkpoint path or folder.'					)
     train_parser.add_argument(
         '--pytorch_dump_output' ,  type=lowerCAmelCase_ ,  required=lowerCAmelCase_ ,  help='Path to the PyTorch saved model output.'					)
     train_parser.add_argument('--config' ,  type=lowerCAmelCase_ ,  default='' ,  help='Configuration file path or folder.'					)
     train_parser.add_argument(
         '--finetuning_task_name' ,  type=lowerCAmelCase_ ,  default=lowerCAmelCase_ ,  help='Optional fine-tuning task name if the TF model was a finetuned model.' ,  )
     train_parser.set_defaults(func=lowerCAmelCase_					)






  def __init__(    self			:		List[str] ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		str ,  *lowerCAmelCase_			:		List[Any] ,  )							->						Optional[Any]:
     __lowerCAmelCase							     =     logging.get_logger('transformers-cli/converting'					)

     self._logger.info(f"""Loading model {model_type}"""					)
     __lowerCAmelCase							     =     model_type
     __lowerCAmelCase							     =     tf_checkpoint
     __lowerCAmelCase							     =     pytorch_dump_output
     __lowerCAmelCase							     =     config
     __lowerCAmelCase							     =     finetuning_task_name






  def     lowercase		(    self			:		str					)							->						int:
     if self._model_type == "albert":
        try:
           from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
               convert_tf_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "bert":
        try:
           from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
               convert_tf_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "funnel":
        try:
           from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
               convert_tf_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "t5":
        try:
           from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "gpt":
        from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
            convert_openai_checkpoint_to_pytorch,
        )

        convert_openai_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "transfo_xl":
        try:
           from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
               convert_transfo_xl_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        if "ckpt" in self._tf_checkpoint.lower():
           __lowerCAmelCase							     =     self._tf_checkpoint
           __lowerCAmelCase							     =     ''
        else:
           __lowerCAmelCase							     =     self._tf_checkpoint
           __lowerCAmelCase							     =     ''
        convert_transfo_xl_checkpoint_to_pytorch(
            lowerCAmelCase_ ,  self._config ,  self._pytorch_dump_output ,  lowerCAmelCase_					)
     elif self._model_type == "gpt2":
        try:
           from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
               convert_gpta_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     elif self._model_type == "xlnet":
        try:
           from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
               convert_xlnet_checkpoint_to_pytorch,
           )
        except ImportError:
           raise ImportError(lowerCAmelCase_					)

        convert_xlnet_checkpoint_to_pytorch(
            self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output ,  self._finetuning_task_name					)
     elif self._model_type == "xlm":
        from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
            convert_xlm_checkpoint_to_pytorch,
        )

        convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint ,  self._pytorch_dump_output					)
     elif self._model_type == "lxmert":
        from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
            convert_lxmert_checkpoint_to_pytorch,
        )

        convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint ,  self._pytorch_dump_output					)
     elif self._model_type == "rembert":
        from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
            convert_rembert_tf_checkpoint_to_pytorch,
        )

        convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,  self._config ,  self._pytorch_dump_output					)
     else:
        raise ValueError(
            '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]'					)








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   (   _UpperCamelCase		,   unittest.TestCase   ):

  """simple docstring"""


  a_      =			DanceDiffusionPipeline
  a_      =			UNCONDITIONAL_AUDIO_GENERATION_PARAMS
  a_      =			PipelineTesterMixin.required_optional_params - {
      """callback""",
      """latents""",
      """callback_steps""",
      """output_type""",
      """num_images_per_prompt""",
  }
  a_      =			UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
  a_      =			False
  a_      =			False






  def     lowercase		(    self			:		List[Any]					)							->						Dict:
     torch.manual_seed(0					)
     __lowerCAmelCase							     =     UNetaDModel(
         block_out_channels=(3_2, 3_2, 6_4) ,  extra_in_channels=1_6 ,  sample_size=5_1_2 ,  sample_rate=1_6_0_0_0 ,  in_channels=2 ,  out_channels=2 ,  flip_sin_to_cos=lowerCAmelCase_ ,  use_timestep_embedding=lowerCAmelCase_ ,  time_embedding_type='fourier' ,  mid_block_type='UNetMidBlock1D' ,  down_block_types=('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D') ,  up_block_types=('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip') ,  )
     __lowerCAmelCase							     =     IPNDMScheduler()

     __lowerCAmelCase							     =     {
         'unet': unet,
         'scheduler': scheduler,
     }
     return components






  def     lowercase		(    self			:		Tuple ,  lowerCAmelCase_			:		Tuple ,  lowerCAmelCase_			:		List[str]=0					)							->						Any:
     if str(lowerCAmelCase_					).startswith('mps'					):
        __lowerCAmelCase							     =     torch.manual_seed(lowerCAmelCase_					)
     else:
        __lowerCAmelCase							     =     torch.Generator(device=lowerCAmelCase_					).manual_seed(lowerCAmelCase_					)
     __lowerCAmelCase							     =     {
         'batch_size': 1,
         'generator': generator,
         'num_inference_steps': 4,
     }
     return inputs






  def     lowercase		(    self			:		Union[str, Any]					)							->						int:
     __lowerCAmelCase							     =     'cpu'  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase							     =     self.get_dummy_components()
     __lowerCAmelCase							     =     DanceDiffusionPipeline(**lowerCAmelCase_					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     self.get_dummy_inputs(lowerCAmelCase_					)
     __lowerCAmelCase							     =     pipe(**lowerCAmelCase_					)
     __lowerCAmelCase							     =     output.audios

     __lowerCAmelCase							     =     audio[0, -3:, -3:]

     assert audio.shape == (1, 2, components["unet"].sample_size)
     __lowerCAmelCase							     =     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     lowercase		(    self			:		Union[str, Any]					)							->						Tuple:
     return super().test_save_load_local()






  @skip_mps
  def     lowercase		(    self			:		List[str]					)							->						Dict:
     return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3					)






  @skip_mps
  def     lowercase		(    self			:		str					)							->						List[str]:
     return super().test_save_load_optional_components()






  @skip_mps
  def     lowercase		(    self			:		List[Any]					)							->						List[str]:
     return super().test_attention_slicing_forward_pass()






  def     lowercase		(    self			:		str					)							->						int:
     super().test_inference_batch_single_identical(expected_max_diff=3e-3					)





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

  """simple docstring"""


  def     lowercase		(    self			:		Any					)							->						Union[str, Any]:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()






  def     lowercase		(    self			:		List[str]					)							->						List[str]:
     __lowerCAmelCase							     =     torch_device

     __lowerCAmelCase							     =     DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.manual_seed(0					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_ ,  num_inference_steps=1_0_0 ,  audio_length_in_s=4.0_96					)
     __lowerCAmelCase							     =     output.audios

     __lowerCAmelCase							     =     audio[0, -3:, -3:]

     assert audio.shape == (1, 2, pipe.unet.sample_size)
     __lowerCAmelCase							     =     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     lowercase		(    self			:		Tuple					)							->						Dict:
     __lowerCAmelCase							     =     torch_device

     __lowerCAmelCase							     =     DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k' ,  torch_dtype=torch.floataa					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.manual_seed(0					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_ ,  num_inference_steps=1_0_0 ,  audio_length_in_s=4.0_96					)
     __lowerCAmelCase							     =     output.audios

     __lowerCAmelCase							     =     audio[0, -3:, -3:]

     assert audio.shape == (1, 2, pipe.unet.sample_size)
     __lowerCAmelCase							     =     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

