


import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock

import torch
from accelerate.utils import write_basic_config

from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
from transformers.utils import is_apex_available


logging.basicConfig(level=logging.DEBUG)

__UpperCamelCase       :       List[Any]						       =				logging.getLogger()

def 			_a  (				):







 """simple docstring"""



 UpperCamelCase__					:    int          =   argparse.ArgumentParser()
 parser.add_argument('''-f'''     )
 UpperCamelCase__					:    Dict          =   parser.parse_args()
 return args.f

def 			_a  (				SCREAMING_SNAKE_CASE	:				Optional[Any]     ):







 """simple docstring"""



 UpperCamelCase__					:    Optional[Any]          =   {}
 UpperCamelCase__					:    str          =   os.path.join(SCREAMING_SNAKE_CASE    , '''all_results.json'''     )
 if os.path.exists(SCREAMING_SNAKE_CASE     ):
  with open(SCREAMING_SNAKE_CASE    , '''r'''     ) as f:
   UpperCamelCase__					:    Any          =   json.load(SCREAMING_SNAKE_CASE     )
 else:
  raise ValueError(F"can't find {path}"     )
 return results

def 			_a  (				):







 """simple docstring"""



 UpperCamelCase__					:    Dict          =   torch.cuda.is_available() and torch_device == '''cuda'''
 return is_using_cuda and is_apex_available()


__UpperCamelCase       :       Any						       =				logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)






class       __magic_name__	(     __lowerCAmelCase):


     @classmethod
     def      UpperCAmelCase__	(      cls							:     int			)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    List[str]          =   tempfile.mkdtemp()
      UpperCamelCase__					:    Any          =   os.path.join(cls.tmpdir							,	'''default_config.yml'''			)
      write_basic_config(save_location=cls.configPath			)
      UpperCamelCase__					:    Union[str, Any]          =   ['''accelerate''', '''launch''', '''--config_file''', cls.configPath]


     @classmethod
     def      UpperCAmelCase__	(      cls							:     int			)  ->      Dict:





      '''simple docstring'''






      shutil.rmtree(cls.tmpdir			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      str:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    int          =   F"\n            {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --seed=42\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      if is_cuda_and_apex_available():
       testargs.append('''--fp16'''			)

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Any          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_accuracy''']							,	0.75			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''glue_no_trainer'''			)			)			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Optional[Any]			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    Any          =   F"\n            {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --block_size 128\n            --per_device_train_batch_size 5\n            --per_device_eval_batch_size 5\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      if torch.cuda.device_count() > 1:
       # Skipping because there are not enough batches to train the model + would need a drop_last to work.
       return

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Optional[int]          =   get_results(lowerCamelCase__			)
      self.assertLess(result['''perplexity''']							,	100			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''clm_no_trainer'''			)			)			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Any			)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Optional[Any]          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    Tuple          =   F"\n            {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --output_dir {tmp_dir}\n            --num_train_epochs=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    str          =   get_results(lowerCamelCase__			)
      self.assertLess(result['''perplexity''']							,	42			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''mlm_no_trainer'''			)			)			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      Dict:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   7 if get_gpu_count() > 1 else 2

      UpperCamelCase__					:    Optional[int]          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    List[str]          =   F"\n            {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/conll/sample.json\n            --validation_file tests/fixtures/tests_samples/conll/sample.json\n            --output_dir {tmp_dir}\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=2\n            --num_train_epochs={epochs}\n            --seed 7\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Optional[int]          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_accuracy''']							,	0.75			)
      self.assertLess(result['''train_loss''']							,	0.5			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''ner_no_trainer'''			)			)			)


     @unittest.skip(reason='''Fix me @muellerzr'''			)
     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     int			)  ->      Optional[int]:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    str          =   F"\n            {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --seed=42\n            --max_train_steps=10\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Dict          =   get_results(lowerCamelCase__			)
      # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics.
      self.assertGreaterEqual(result['''eval_f1''']							,	28			)
      self.assertGreaterEqual(result['''eval_exact''']							,	28			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''qa_no_trainer'''			)			)			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     str			)  ->      Tuple:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    Optional[int]          =   F"\n            {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=20\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    List[str]          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_accuracy''']							,	0.8			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''swag_no_trainer'''			)			)			)


     @slow
     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Union[str, Any]			)  ->      int:





      '''simple docstring'''






      UpperCamelCase__					:    Union[str, Any]          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    List[Any]          =   F"\n            {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py\n            --model_name_or_path t5-small\n            --train_file tests/fixtures/tests_samples/xsum/sample.json\n            --validation_file tests/fixtures/tests_samples/xsum/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=50\n            --num_warmup_steps=8\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    int          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_rouge1''']							,	10			)
      self.assertGreaterEqual(result['''eval_rouge2''']							,	2			)
      self.assertGreaterEqual(result['''eval_rougeL''']							,	7			)
      self.assertGreaterEqual(result['''eval_rougeLsum''']							,	7			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''summarization_no_trainer'''			)			)			)


     @slow
     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Tuple			)  ->      List[str]:





      '''simple docstring'''






      UpperCamelCase__					:    str          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    Optional[int]          =   F"\n            {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py\n            --model_name_or_path sshleifer/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --max_train_steps=50\n            --num_warmup_steps=8\n            --num_beams=6\n            --learning_rate=3e-3\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n            --checkpointing_steps epoch\n            --with_tracking\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    str          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_bleu''']							,	30			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''epoch_0'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''translation_no_trainer'''			)			)			)


     @slow
     def      UpperCAmelCase__	(      self							:     Dict			)  ->      Any:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   logging.StreamHandler(sys.stdout			)
      logger.addHandler(lowerCamelCase__			)

      UpperCamelCase__					:    int          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    Any          =   F"\n            {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py\n            --dataset_name huggingface/semantic-segmentation-test-sample\n            --output_dir {tmp_dir}\n            --max_train_steps=10\n            --num_warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --checkpointing_steps epoch\n        ".split()

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Dict          =   get_results(lowerCamelCase__			)
      self.assertGreaterEqual(result['''eval_overall_accuracy''']							,	0.10			)


     @mock.patch.dict(os.environ							,	{'''WANDB_MODE''': '''offline'''}			)
     def      UpperCAmelCase__	(      self							:     Optional[int]			)  ->      Optional[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    Any          =   self.get_auto_remove_tmp_dir()
      UpperCamelCase__					:    str          =   F"\n            {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py\n            --model_name_or_path google/vit-base-patch16-224-in21k\n            --dataset_name hf-internal-testing/cats_vs_dogs_sample\n            --learning_rate 1e-4\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --max_train_steps 2\n            --train_val_split 0.1\n            --seed 42\n            --output_dir {tmp_dir}\n            --with_tracking\n            --checkpointing_steps 1\n        ".split()

      if is_cuda_and_apex_available():
       testargs.append('''--fp16'''			)

      run_command(self._launch_args + testargs			)
      UpperCamelCase__					:    Optional[Any]          =   get_results(lowerCamelCase__			)
      # The base model scores a 25%
      self.assertGreaterEqual(result['''eval_accuracy''']							,	0.6			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''step_1'''			)			)			)
      self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__							,	'''image_classification_no_trainer'''			)			)			)






from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand

def 			_a  (				SCREAMING_SNAKE_CASE	:				Namespace     ):







 """simple docstring"""



 return ConvertCommand(
     args.model_type    , args.tf_checkpoint    , args.pytorch_dump_output    , args.config    , args.finetuning_task_name     )


__UpperCamelCase       :       List[Any]						       =				"\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       __magic_name__	(     __lowerCAmelCase):


     @staticmethod
     def      UpperCAmelCase__	(      lowerCamelCase__							:     ArgumentParser			)  ->      Optional[int]:





      '''simple docstring'''






      UpperCamelCase__					:    int          =   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							:     Optional[Any]							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     str							,	lowerCamelCase__							:     str							,	*lowerCamelCase__							:     Optional[int]							,	)  ->      List[Any]:





      '''simple docstring'''






      UpperCamelCase__					:    List[Any]          =   logging.get_logger('''transformers-cli/converting'''			)

      self._logger.info(F"Loading model {model_type}"			)
      UpperCamelCase__					:    List[str]          =   model_type
      UpperCamelCase__					:    Optional[int]          =   tf_checkpoint
      UpperCamelCase__					:    List[Any]          =   pytorch_dump_output
      UpperCamelCase__					:    List[Any]          =   config
      UpperCamelCase__					:    Any          =   finetuning_task_name


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





      '''simple docstring'''






      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():
        UpperCamelCase__					:    str          =   self._tf_checkpoint
        UpperCamelCase__					:    List[Any]          =   ''''''
       else:
        UpperCamelCase__					:    Any          =   self._tf_checkpoint
        UpperCamelCase__					:    List[Any]          =   ''''''
       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]'''			)


