




import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


lowerCamelCase				:		Any     =   logging.getLogger(__name__)

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       List[str]	,							lowercase	:       List[Any]     ):


      '''simple docstring'''



      return (preds == labels).mean()







@dataclass
class   A:



 '''simple docstring'''


 UpperCamelCase						   =						field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}   )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}   )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}   )
 UpperCamelCase						   =						field(
     default=UpperCamelCase							,      metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}							,      )







@dataclass
class   A:



 '''simple docstring'''


 UpperCamelCase						   =						field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(processors.keys()   )}   )
 UpperCamelCase						   =						field(metadata={'''help''': '''Should contain the 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=UpperCamelCase							,      metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}   )

def 			_SCREAMING_SNAKE_CASE			(							):


      '''simple docstring'''



      lowerCamelCase_		     =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
      lowerCamelCase_     ,				lowerCamelCase_     ,				lowerCamelCase_		     =    parser.parse_args_into_dataclasses()

      if (
          os.path.exists(training_args.output_dir     )
          and os.listdir(training_args.output_dir     )
          and training_args.do_train
          and not training_args.overwrite_output_dir
      ):
            raise ValueError(
                f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
                ' --overwrite_output_dir to overcome.'     )

      # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'	,							datefmt='%m/%d/%Y %H:%M:%S'	,							level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN	,							)
      logger.warning(
          'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'	,							training_args.local_rank	,							training_args.device	,							training_args.n_gpu	,							bool(training_args.local_rank != -1     )	,							training_args.fpaa	,							)
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(training_args.local_rank     ):
            transformers.utils.logging.set_verbosity_info()
            transformers.utils.logging.enable_default_handler()
            transformers.utils.logging.enable_explicit_format()
      logger.info('Training/evaluation parameters %s'	,							lowercase     )

      # Set seed
      set_seed(training_args.seed     )

      try:
            lowerCamelCase_		     =    processors[data_args.task_name]()
            lowerCamelCase_		     =    processor.get_labels()
            lowerCamelCase_		     =    len(lowercase     )
      except KeyError:
            raise ValueError('Task not found: %s' % (data_args.task_name)     )

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.

      lowerCamelCase_		     =    AutoConfig.from_pretrained(
          model_args.config_name if model_args.config_name else model_args.model_name_or_path	,							num_labels=lowercase	,							finetuning_task=data_args.task_name	,							cache_dir=model_args.cache_dir	,							)
      lowerCamelCase_		     =    AutoTokenizer.from_pretrained(
          model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path	,							cache_dir=model_args.cache_dir	,							)
      lowerCamelCase_		     =    AutoModelForMultipleChoice.from_pretrained(
          model_args.model_name_or_path	,							from_tf=bool('.ckpt' in model_args.model_name_or_path     )	,							config=lowercase	,							cache_dir=model_args.cache_dir	,							)

      # Get datasets
      lowerCamelCase_		     =    (
          MultipleChoiceDataset(
              data_dir=data_args.data_dir	,							tokenizer=lowercase	,							task=data_args.task_name	,							max_seq_length=data_args.max_seq_length	,							overwrite_cache=data_args.overwrite_cache	,							mode=Split.train	,							)
          if training_args.do_train
          else None
      )
      lowerCamelCase_		     =    (
          MultipleChoiceDataset(
              data_dir=data_args.data_dir	,							tokenizer=lowercase	,							task=data_args.task_name	,							max_seq_length=data_args.max_seq_length	,							overwrite_cache=data_args.overwrite_cache	,							mode=Split.dev	,							)
          if training_args.do_eval
          else None
      )

      def compute_metrics(lowercase	:       EvalPrediction     ) -> Dict:
            lowerCamelCase_		     =    np.argmax(p.predictions	,							axis=1     )
            return {"acc": simple_accuracy(lowercase	,							p.label_ids     )}

      # Data collator
      lowerCamelCase_		     =    DataCollatorWithPadding(lowercase	,							pad_to_multiple_of=8     ) if training_args.fpaa else None

      # Initialize our Trainer
      lowerCamelCase_		     =    Trainer(
          model=lowercase	,							args=lowercase	,							train_dataset=lowercase	,							eval_dataset=lowercase	,							compute_metrics=lowercase	,							data_collator=lowercase	,							)

      # Training
      if training_args.do_train:
            trainer.train(
                model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path     ) else None     )
            trainer.save_model()
            # For convenience, we also re-save the tokenizer to the same directory,
            # so that you can share your model easily on huggingface.co/models =)
            if trainer.is_world_master():
                  tokenizer.save_pretrained(training_args.output_dir     )

    # Evaluation
      lowerCamelCase_		     =    {}
      if training_args.do_eval:
            logger.info('*** Evaluate ***'     )

            lowerCamelCase_		     =    trainer.evaluate()

            lowerCamelCase_		     =    os.path.join(training_args.output_dir	,							'eval_results.txt'     )
            if trainer.is_world_master():
                  with open(lowercase	,							'w'     ) as writer:
                        logger.info('***** Eval results *****'     )
                        for key, value in result.items():
                              logger.info('  %s = %s'	,							lowercase	,							lowercase     )
                              writer.write('%s = %s\n' % (key, value)     )

                        results.update(lowercase     )

      return results

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       str     ):


      '''simple docstring'''



      main()


if __name__ == "__main__":
 main()









import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
lowerCamelCase				:		Union[str, Any]     =   "src/diffusers"

# Matches is_xxx_available()
lowerCamelCase				:		Dict     =   re.compile(r"is\_([a-z_]*)_available\(\)")
# Matches from xxx import bla
lowerCamelCase				:		Union[str, Any]     =   re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")


lowerCamelCase				:		Any     =   "\n{0} = None\n"

lowerCamelCase				:		List[str]     =   "\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n"


lowerCamelCase				:		str     =   "\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       Optional[Any]     ):


      '''simple docstring'''



      lowerCamelCase_		     =    _re_backend.findall(lowercase     )
      if len(lowercase     ) == 0:
            return None

      return "_and_".join(lowercase     )

def 			_SCREAMING_SNAKE_CASE			(							):


      '''simple docstring'''



      with open(os.path.join(lowercase	,							'__init__.py'     )	,							'r'	,							encoding='utf-8'	,							newline='\n'     ) as f:
            lowerCamelCase_		     =    f.readlines()

      # Get to the point we do the actual imports for type checking
      lowerCamelCase_		     =    0
      lowerCamelCase_		     =    {}
      # Go through the end of the file
      while line_index < len(lowercase     ):
            # If the line contains is_backend_available, we grab all objects associated with the `else` block
            lowerCamelCase_		     =    find_backend(lines[line_index]     )
            if backend is not None:
                  while not lines[line_index].startswith('else:'     ):
                        line_index += 1
                  line_index += 1
                  lowerCamelCase_		     =    []
                  # Until we unindent, add backend objects to the list
                  while line_index < len(lowercase     ) and len(lines[line_index]     ) > 1:
                        lowerCamelCase_		     =    lines[line_index]
                        lowerCamelCase_		     =    _re_single_line_import.search(lowercase     )
                        if single_line_import_search is not None:
                              objects.extend(single_line_import_search.groups()[0].split(', '     )     )
                        elif line.startswith(' ' * 8     ):
                              objects.append(line[8:-2]     )
                        line_index += 1

                  if len(lowercase     ) > 0:
                        lowerCamelCase_		     =    objects
            else:
                  line_index += 1

      return backend_specific_objects

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       List[str]	,							lowercase	:       str     ):


      '''simple docstring'''



      if name.isupper():
            return DUMMY_CONSTANT.format(lowercase     )
      elif name.islower():
            return DUMMY_FUNCTION.format(lowercase	,							lowercase     )
      else:
            return DUMMY_CLASS.format(lowercase	,							lowercase     )

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       Optional[int]=None     ):


      '''simple docstring'''



      if backend_specific_objects is None:
            lowerCamelCase_		     =    read_init()
      # For special correspondence backend to module name as used in the function requires_modulename
      lowerCamelCase_		     =    {}

      for backend, objects in backend_specific_objects.items():
            lowerCamelCase_		     =    '[' + ', '.join(f"""\"{b}\"""" for b in backend.split('_and_'     )     ) + ']'
            lowerCamelCase_		     =    '# This file is autogenerated by the command `make fix-copies`, do not edit.\n'
            dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
            dummy_file += "\n".join([create_dummy_object(lowercase	,							lowercase     ) for o in objects]     )
            lowerCamelCase_		     =    dummy_file

      return dummy_files

def 			_SCREAMING_SNAKE_CASE			(							lowercase	:       Optional[int]=False     ):


      '''simple docstring'''



      lowerCamelCase_		     =    create_dummy_files()
      # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
      lowerCamelCase_		     =    {'torch': 'pt'}

      # Locate actual dummy modules and read their content.
      lowerCamelCase_		     =    os.path.join(lowercase	,							'utils'     )
      lowerCamelCase_		     =    {
          backend: os.path.join(lowercase	,							f"""dummy_{short_names.get(lowercase	,							lowercase     )}_objects.py"""     )
          for backend in dummy_files.keys()
      }

      lowerCamelCase_		     =    {}
      for backend, file_path in dummy_file_paths.items():
            if os.path.isfile(lowercase     ):
                  with open(lowercase	,							'r'	,							encoding='utf-8'	,							newline='\n'     ) as f:
                        lowerCamelCase_		     =    f.read()
            else:
                  lowerCamelCase_		     =    ''

      for backend in dummy_files.keys():
            if dummy_files[backend] != actual_dummies[backend]:
                  if overwrite:
                        print(
                            f"""Updating diffusers.utils.dummy_{short_names.get(lowercase	,							lowercase     )}_objects.py as the main """
                            '__init__ has new objects.'     )
                        with open(dummy_file_paths[backend]	,							'w'	,							encoding='utf-8'	,							newline='\n'     ) as f:
                              f.write(dummy_files[backend]     )
                  else:
                        raise ValueError(
                            'The main __init__ has objects that are not present in '
                            f"""diffusers.utils.dummy_{short_names.get(lowercase	,							lowercase     )}_objects.py. Run `make fix-copies` """
                            'to fix this.'     )


if __name__ == "__main__":
 lowerCamelCase				:		List[Any]     =   argparse.ArgumentParser()
 parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
 lowerCamelCase				:		Tuple     =   parser.parse_args()

 check_dummies(args.fix_and_overwrite)



