





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)

_lowerCamelCase             =      logging.getLogger()




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




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




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     Dict	=		torch.cuda.is_available() and torch_device == '''cuda'''
       return is_using_cuda and is_apex_available()


_lowerCamelCase             =      logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







class 			__A       (      __lowerCAmelCase  ):




      """simple docstring"""







      @classmethod
      def 				__snake_case			(		cls):



             """simple docstring"""





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


      @classmethod
      def 				__snake_case			(		cls):



             """simple docstring"""





             shutil.rmtree(cls.tmpdir)


      @mock.patch.dict(os.environ      ,							{'''WANDB_MODE''': '''offline'''})
      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     int	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Optional[Any]	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Optional[Any]	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





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

             _lowerCamelCase							:     Optional[int]	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Union[str, Any]	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     int	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Union[str, Any]	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     str	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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 				__snake_case			(		self):



             """simple docstring"""





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

             _lowerCamelCase							:     int	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     Dict	=		get_results(lowerCamelCase__)
             self.assertGreaterEqual(result['''eval_overall_accuracy''']      ,							0.10)



      @mock.patch.dict(os.environ      ,							{'''WANDB_MODE''': '''offline'''})
      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Any	=		self.get_auto_remove_tmp_dir()
             _lowerCamelCase							:     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)
             _lowerCamelCase							:     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''')))








import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


_lowerCamelCase			       =      logging.get_logger(__name__)







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()  )}  )
      UpperCAmelCase__						=      field(
          metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}  )
      UpperCAmelCase__						=      field(
          default=128 ,metadata={
              """help""": (
                  """The maximum total input sequence length after tokenization. Sequences longer """
                  """than this will be truncated, sequences shorter will be padded."""
              )
          } ,)
      UpperCAmelCase__						=      field(
          default=lowerCamelCase__ ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		self.task_name.lower()







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      """train"""
      UpperCAmelCase__						=      """dev"""
      UpperCAmelCase__						=      """test"""







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42


      def __init__(		self      ,							a__      ,							a__      ,							a__ = None      ,							a__ = Split.train      ,							a__ = None      ,							):



             """simple docstring"""





             warnings.warn(
                 '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '''
                 '''library. You can have a look at this example script for pointers: '''
                 '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''      ,							a__      ,							)
             _lowerCamelCase							:     Optional[Any]	=		args
             _lowerCamelCase							:     Tuple	=		glue_processors[args.task_name]()
             _lowerCamelCase							:     Any	=		glue_output_modes[args.task_name]
             if isinstance(a__      ,							a__):
                    try:
                           _lowerCamelCase							:     List[Any]	=		Split[mode]
                    except KeyError:
                           raise KeyError('''mode is not a valid split name''')
        # Load data features from cache or dataset file
             _lowerCamelCase							:     Tuple	=		os.path.join(
                 cache_dir if cache_dir is not None else args.data_dir      ,							F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}"""      ,							)
             _lowerCamelCase							:     int	=		self.processor.get_labels()
             if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
                 "RobertaTokenizer",
                 "RobertaTokenizerFast",
                 "XLMRobertaTokenizer",
                 "BartTokenizer",
                 "BartTokenizerFast",
             ):
                    # HACK(label indices are swapped in RoBERTa pretrained model)
                    _lowerCamelCase,  _lowerCamelCase							:     Union[str, Any]	=		label_list[2], label_list[1]
             _lowerCamelCase							:     str	=		label_list

             # Make sure only the first process in distributed training processes the dataset,
             # and the others will use the cache.
             _lowerCamelCase							:     Any	=		cached_features_file + '''.lock'''
             with FileLock(a__):
                    if os.path.exists(a__) and not args.overwrite_cache:
                           _lowerCamelCase							:     Any	=		time.time()
                           _lowerCamelCase							:     Optional[Any]	=		torch.load(a__)
                           logger.info(
                               F"""Loading features from cached file {cached_features_file} [took %.3f s]"""      ,							time.time() - start)
                    else:
                           logger.info(F"""Creating features from dataset file at {args.data_dir}""")

                           if mode == Split.dev:
                                  _lowerCamelCase							:     List[str]	=		self.processor.get_dev_examples(args.data_dir)
                           elif mode == Split.test:
                                  _lowerCamelCase							:     str	=		self.processor.get_test_examples(args.data_dir)
                           else:
                                  _lowerCamelCase							:     List[Any]	=		self.processor.get_train_examples(args.data_dir)
                           if limit_length is not None:
                                  _lowerCamelCase							:     List[Any]	=		examples[:limit_length]
                           _lowerCamelCase							:     List[str]	=		glue_convert_examples_to_features(
                               a__      ,							a__      ,							max_length=args.max_seq_length      ,							label_list=a__      ,							output_mode=self.output_mode      ,							)
                           _lowerCamelCase							:     int	=		time.time()
                           torch.save(self.features      ,							a__)
                           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                           logger.info(
                               F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""")


      def __len__(		self):



             """simple docstring"""





             return len(self.features)


      def __getitem__(		self      ,							a__):



             """simple docstring"""





             return self.features[i]



      def 				__snake_case			(		self):



             """simple docstring"""





             return self.label_list

