


'''simple docstring'''






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


a_   :      int				    =      logging.getLogger(__name__)






def 		_A			(lowerCAmelCase__					:int			,  lowerCAmelCase__					:Dict						)				->					Optional[int]:




     '''simple docstring'''



     return (preds == labels).mean()




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





@dataclass
class 	a       :
 _lowerCAmelCase	   =		field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys()    )}    )
 _lowerCAmelCase	   =		field(metadata={"""help""": """Should contain the data files for the task."""}    )
 _lowerCAmelCase	   =		field(
     default=1_2_8					,			metadata={
         """help""": (
             """The maximum total input sequence length after tokenization. Sequences longer """
             """than this will be truncated, sequences shorter will be padded."""
         )
     }					,			)
 _lowerCAmelCase	   =		field(
     default=_SCREAMING_SNAKE_CASE					,			metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )






def 		_A			()				->					Optional[int]:




     '''simple docstring'''



     _a      =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
     _a ,				_a ,				_a      =							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'			,  lowerCAmelCase__						)

     # Set seed
     set_seed(training_args.seed						)

     try:
          _a      =							processors[data_args.task_name]()
          _a      =							processor.get_labels()
          _a      =							len(lowerCAmelCase__						)
     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.

     _a      =							AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path			,  num_labels=lowerCAmelCase__			,  finetuning_task=data_args.task_name			,  cache_dir=model_args.cache_dir			,  )
     _a      =							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			,  )
     _a      =							AutoModelForMultipleChoice.from_pretrained(
         model_args.model_name_or_path			,  from_tf=bool('.ckpt' in model_args.model_name_or_path						)			,  config=lowerCAmelCase__			,  cache_dir=model_args.cache_dir			,  )

     # Get datasets
     _a      =							(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir			,  tokenizer=lowerCAmelCase__			,  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
     )
     _a      =							(
         MultipleChoiceDataset(
             data_dir=data_args.data_dir			,  tokenizer=lowerCAmelCase__			,  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(lowerCAmelCase__					:EvalPrediction						) -> Dict:
          _a      =							np.argmax(p.predictions			,  axis=1						)
          return {"acc": simple_accuracy(lowerCAmelCase__			,  p.label_ids						)}

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

     # Initialize our Trainer
     _a      =							Trainer(
         model=lowerCAmelCase__			,  args=lowerCAmelCase__			,  train_dataset=lowerCAmelCase__			,  eval_dataset=lowerCAmelCase__			,  compute_metrics=lowerCAmelCase__			,  data_collator=lowerCAmelCase__			,  )

     # 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
     _a      =							{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'						)

          _a      =							trainer.evaluate()

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

                    results.update(lowerCAmelCase__						)

     return results






def 		_A			(lowerCAmelCase__					:List[str]						)				->					List[Any]:




     '''simple docstring'''



     main()


if __name__ == "__main__":
 main()





'''simple docstring'''






import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


a_   :      List[str]				    =      logging.get_logger(__name__)

a_   :      str				    =      {
    "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json",
}




class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		"""git_vision_model"""
 def __init__(	self ,			__magic_name__=7_68 ,			__magic_name__=30_72 ,			__magic_name__=12 ,			__magic_name__=12 ,			__magic_name__=3 ,			__magic_name__=2_24 ,			__magic_name__=16 ,			__magic_name__="quick_gelu" ,			__magic_name__=1e-5 ,			__magic_name__=0.0 ,			__magic_name__=0.0_2 ,			**__magic_name__ ,			)   ->							Union[str, Any]:
      super().__init__(**__magic_name__  )

      _a      =							hidden_size
      _a      =							intermediate_size
      _a      =							num_hidden_layers
      _a      =							num_attention_heads
      _a      =							num_channels
      _a      =							patch_size
      _a      =							image_size
      _a      =							initializer_range
      _a      =							attention_dropout
      _a      =							layer_norm_eps
      _a      =							hidden_act




 @classmethod
 def 							__UpperCAmelCase						(	cls ,			__magic_name__ ,			**__magic_name__  )   ->							"PretrainedConfig":
      cls._set_token_in_kwargs(__magic_name__  )

      _a ,				_a      =							cls.get_config_dict(__magic_name__ ,			**__magic_name__  )

      # get the vision config dict if we are loading from GITConfig
      if config_dict.get('model_type'  ) == "git":
           _a      =							config_dict['vision_config']

      if "model_type" in config_dict and hasattr(cls ,			'model_type'  ) and config_dict["model_type"] != cls.model_type:
           logger.warning(
               f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
               f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'  )

      return cls.from_dict(__magic_name__ ,			**__magic_name__  )





class 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		"""git"""
 def __init__(	self ,			__magic_name__=None ,			__magic_name__=3_05_22 ,			__magic_name__=7_68 ,			__magic_name__=6 ,			__magic_name__=12 ,			__magic_name__=30_72 ,			__magic_name__="gelu" ,			__magic_name__=0.1 ,			__magic_name__=0.1 ,			__magic_name__=10_24 ,			__magic_name__=0.0_2 ,			__magic_name__=1e-12 ,			__magic_name__=0 ,			__magic_name__="absolute" ,			__magic_name__=True ,			__magic_name__=False ,			__magic_name__=1_01 ,			__magic_name__=1_02 ,			__magic_name__=None ,			**__magic_name__ ,			)   ->							Optional[int]:
      super().__init__(bos_token_id=__magic_name__ ,			eos_token_id=__magic_name__ ,			pad_token_id=__magic_name__ ,			**__magic_name__  )

      if vision_config is None:
           _a      =							{}
           logger.info('vision_config is None. initializing the GitVisionConfig with default values.'  )

      _a      =							GitVisionConfig(**__magic_name__  )
      _a      =							vocab_size
      _a      =							hidden_size
      _a      =							num_hidden_layers
      _a      =							num_attention_heads
      _a      =							hidden_act
      _a      =							intermediate_size
      _a      =							hidden_dropout_prob
      _a      =							attention_probs_dropout_prob
      _a      =							max_position_embeddings
      _a      =							initializer_range
      _a      =							layer_norm_eps
      _a      =							position_embedding_type
      _a      =							use_cache
      _a      =							tie_word_embeddings
      _a      =							num_image_with_embedding

      _a      =							bos_token_id
      _a      =							eos_token_id




 def 							__UpperCAmelCase						(	self  )   ->							List[str]:
      _a      =							copy.deepcopy(self.__dict__  )
      _a      =							self.vision_config.to_dict()
      _a      =							self.__class__.model_type
      return output

