


"""simple docstring"""







import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

lowerCamelCase_       :       str      						=  logging.getLogger(__name__)






@dataclass
class 				__A    :






 """simple docstring"""




 __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"},   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},   )
 __lowerCAmelCase			 =  field(
     default="main",   metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={
         "help": (
             "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
             "with private models)."
         )
     },   )






@dataclass
class 				__A    :






 """simple docstring"""




 __lowerCAmelCase			 =  field(default=_SCREAMING_SNAKE_CASE,   metadata={"help": "The input training data file (a text file)."}      )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={"help": "Overwrite the cached training and evaluation sets"}      )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={"help": "The number of processes to use for the preprocessing."},   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={
         "help": (
             "The maximum total input sequence length after tokenization. If passed, sequences longer "
             "than this will be truncated, sequences shorter will be padded."
         )
     },   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={
         "help": (
             "Whether to pad all samples to the maximum sentence length. "
             "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
             "efficient on GPU but very bad for TPU."
         )
     },   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of training examples to this "
             "value if set."
         )
     },   )
 __lowerCAmelCase			 =  field(
     default=_SCREAMING_SNAKE_CASE,   metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
             "value if set."
         )
     },   )


 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Any:
     if self.train_file is not None:
         a					=self.train_file.split('''.'''						)[-1]
         assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
     if self.validation_file is not None:
         a					=self.validation_file.split('''.'''						)[-1]
         assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."






@dataclass
class 				__A    :






 """simple docstring"""




 __lowerCAmelCase			 =  42
 __lowerCAmelCase			 =  True
 __lowerCAmelCase			 =  None
 __lowerCAmelCase			 =  None


 def __call__(		self			,   __A						) ->					Optional[Any]:
     a					='''label''' if '''label''' in features[0].keys() else '''labels'''
     a					=[feature.pop(__A						) for feature in features]
     a					=len(__A						)
     a					=len(features[0]['''input_ids''']						)
     a					=[
         [{k: v[i] for k, v in feature.items()} for i in range(__A						)] for feature in features
     ]
     a					=list(chain(*__A						)						)

     a					=self.tokenizer.pad(
         __A			,   padding=self.padding			,   max_length=self.max_length			,   pad_to_multiple_of=self.pad_to_multiple_of			,   return_tensors='''pt'''			,   )

     # Un-flatten
     a					={k: v.view(__A			,   __A			,   -1						) for k, v in batch.items()}
     # Add back labels
     a					=torch.tensor(__A			,   dtype=torch.intaa						)
     return batch

def _A						(						):







    """simple docstring"""
    a					=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
    if len(sys.argv		) == 2 and sys.argv[1].endswith('''.json'''		):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        a		,				a		,				a					=parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
    else:
        a		,				a		,				a					=parser.parse_args_into_dataclasses()

    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    send_example_telemetry('''run_swag'''	,   lowercase	,   lowercase		)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''	,   datefmt='''%m/%d/%Y %H:%M:%S'''	,   handlers=[logging.StreamHandler(sys.stdout		)]	,   )

    if training_args.should_log:
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
        transformers.utils.logging.set_verbosity_info()

    a					=training_args.get_process_log_level()
    logger.setLevel(lowercase		)
    datasets.utils.logging.set_verbosity(lowercase		)
    transformers.utils.logging.set_verbosity(lowercase		)
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
        + f'''distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}'''		)
    logger.info(f'''Training/evaluation parameters {training_args}'''		)

    # Detecting last checkpoint.
    a					=None
    if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
        a					=get_last_checkpoint(training_args.output_dir		)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
            raise ValueError(
                f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                '''Use --overwrite_output_dir to overcome.'''		)
        elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
            logger.info(
                f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''		)

    # Set seed before initializing model.
    set_seed(training_args.seed		)

    # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
    # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
    # (the dataset will be downloaded automatically from the datasets Hub).

    # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
    # 'text' is found. You can easily tweak this behavior (see below).

    # In distributed training, the load_dataset function guarantee that only one local process can concurrently
    # download the dataset.
    if data_args.train_file is not None or data_args.validation_file is not None:
        a					={}
        if data_args.train_file is not None:
            a					=data_args.train_file
        if data_args.validation_file is not None:
            a					=data_args.validation_file
        a					=data_args.train_file.split('''.'''		)[-1]
        a					=load_dataset(
            lowercase	,   data_files=lowercase	,   cache_dir=model_args.cache_dir	,   use_auth_token=True if model_args.use_auth_token else None	,   )
    else:
        # Downloading and loading the swag dataset from the hub.
        a					=load_dataset(
            '''swag'''	,   '''regular'''	,   cache_dir=model_args.cache_dir	,   use_auth_token=True if model_args.use_auth_token else None	,   )
    # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
    # https://huggingface.co/docs/datasets/loading_datasets.html.

    # 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	,   cache_dir=model_args.cache_dir	,   revision=model_args.model_revision	,   use_auth_token=True if model_args.use_auth_token else None	,   )
    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	,   use_fast=model_args.use_fast_tokenizer	,   revision=model_args.model_revision	,   use_auth_token=True if model_args.use_auth_token else None	,   )
    a					=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	,   revision=model_args.model_revision	,   use_auth_token=True if model_args.use_auth_token else None	,   )

    # When using your own dataset or a different dataset from swag, you will probably need to change this.
    a					=[f'''ending{i}''' for i in range(4		)]
    a					='''sent1'''
    a					='''sent2'''

    if data_args.max_seq_length is None:
        a					=tokenizer.model_max_length
        if max_seq_length > 10_24:
            logger.warning(
                '''The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value'''
                ''' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can'''
                ''' override this default with `--block_size xxx`.'''		)
            a					=10_24
    else:
        if data_args.max_seq_length > tokenizer.model_max_length:
            logger.warning(
                f'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the'''
                f'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.'''		)
        a					=min(data_args.max_seq_length	,   tokenizer.model_max_length		)

    # Preprocessing the datasets.
    def preprocess_function(lowercase		):
        a					=[[context] * 4 for context in examples[context_name]]
        a					=examples[question_header_name]
        a					=[
            [f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(lowercase		)
        ]

        # Flatten out
        a					=list(chain(*lowercase		)		)
        a					=list(chain(*lowercase		)		)

        # Tokenize
        a					=tokenizer(
            lowercase	,   lowercase	,   truncation=lowercase	,   max_length=lowercase	,   padding='''max_length''' if data_args.pad_to_max_length else False	,   )
        # Un-flatten
        return {k: [v[i : i + 4] for i in range(0	,   len(lowercase		)	,   4		)] for k, v in tokenized_examples.items()}

    if training_args.do_train:
        if "train" not in raw_datasets:
            raise ValueError('''--do_train requires a train dataset'''		)
        a					=raw_datasets['''train''']
        if data_args.max_train_samples is not None:
            a					=min(len(lowercase		)	,   data_args.max_train_samples		)
            a					=train_dataset.select(range(lowercase		)		)
        with training_args.main_process_first(desc='''train dataset map pre-processing'''		):
            a					=train_dataset.map(
                lowercase	,   batched=lowercase	,   num_proc=data_args.preprocessing_num_workers	,   load_from_cache_file=not data_args.overwrite_cache	,   )

    if training_args.do_eval:
        if "validation" not in raw_datasets:
            raise ValueError('''--do_eval requires a validation dataset'''		)
        a					=raw_datasets['''validation''']
        if data_args.max_eval_samples is not None:
            a					=min(len(lowercase		)	,   data_args.max_eval_samples		)
            a					=eval_dataset.select(range(lowercase		)		)
        with training_args.main_process_first(desc='''validation dataset map pre-processing'''		):
            a					=eval_dataset.map(
                lowercase	,   batched=lowercase	,   num_proc=data_args.preprocessing_num_workers	,   load_from_cache_file=not data_args.overwrite_cache	,   )

    # Data collator
    a					=(
        default_data_collator
        if data_args.pad_to_max_length
        else DataCollatorForMultipleChoice(tokenizer=lowercase	,   pad_to_multiple_of=8 if training_args.fpaa else None		)
    )

    # Metric
    def compute_metrics(lowercase		):
        a		,				a					=eval_predictions
        a					=np.argmax(lowercase	,   axis=1		)
        return {"accuracy": (preds == label_ids).astype(np.floataa		).mean().item()}

    # Initialize our Trainer
    a					=Trainer(
        model=lowercase	,   args=lowercase	,   train_dataset=train_dataset if training_args.do_train else None	,   eval_dataset=eval_dataset if training_args.do_eval else None	,   tokenizer=lowercase	,   data_collator=lowercase	,   compute_metrics=lowercase	,   )

    # Training
    if training_args.do_train:
        a					=None
        if training_args.resume_from_checkpoint is not None:
            a					=training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            a					=last_checkpoint
        a					=trainer.train(resume_from_checkpoint=lowercase		)
        trainer.save_model()  # Saves the tokenizer too for easy upload
        a					=train_result.metrics

        a					=(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase		)
        )
        a					=min(lowercase	,   len(lowercase		)		)

        trainer.log_metrics('''train'''	,   lowercase		)
        trainer.save_metrics('''train'''	,   lowercase		)
        trainer.save_state()

    # Evaluation
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''		)

        a					=trainer.evaluate()
        a					=data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase		)
        a					=min(lowercase	,   len(lowercase		)		)

        trainer.log_metrics('''eval'''	,   lowercase		)
        trainer.save_metrics('''eval'''	,   lowercase		)

    a					={
        '''finetuned_from''': model_args.model_name_or_path,
        '''tasks''': '''multiple-choice''',
        '''dataset_tags''': '''swag''',
        '''dataset_args''': '''regular''',
        '''dataset''': '''SWAG''',
        '''language''': '''en''',
    }

    if training_args.push_to_hub:
        trainer.push_to_hub(**lowercase		)
    else:
        trainer.create_model_card(**lowercase		)
def _A						(						lowercase		):







    """simple docstring"""
    main()


if __name__ == "__main__":
       main()



"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


lowerCamelCase_       :       List[Any]      						=  logging.get_logger(__name__)


if is_vision_available():
       import PIL






class 				__A    (	_SCREAMING_SNAKE_CASE      ):






 """simple docstring"""




 __lowerCAmelCase			 =  ["pixel_values"]


 def __init__(		self			,   __A = True			,   __A = None			,   __A = PILImageResampling.BICUBIC			,   __A = True			,   __A = None			,   __A = True			,   __A = 1 / 255			,   __A = True			,   __A = None			,   __A = None			,   __A = True			,   **__A			,   ) ->					None:
     super().__init__(**__A						)
     a					=size if size is not None else {'''shortest_edge''': 224}
     a					=get_size_dict(__A			,   default_to_square=__A						)
     a					=crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
     a					=get_size_dict(__A			,   default_to_square=__A			,   param_name='''crop_size'''						)

     a					=do_resize
     a					=size
     a					=resample
     a					=do_center_crop
     a					=crop_size
     a					=do_rescale
     a					=rescale_factor
     a					=do_normalize
     a					=image_mean if image_mean is not None else OPENAI_CLIP_MEAN
     a					=image_std if image_std is not None else OPENAI_CLIP_STD
     a					=do_convert_rgb


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = PILImageResampling.BICUBIC			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     a					=get_size_dict(__A			,   default_to_square=__A						)
     if "shortest_edge" not in size:
         raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''						)
     a					=get_resize_output_image_size(__A			,   size=size['''shortest_edge''']			,   default_to_square=__A						)
     return resize(__A			,   size=__A			,   resample=__A			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     a					=get_size_dict(__A						)
     if "height" not in size or "width" not in size:
         raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''						)
     return center_crop(__A			,   size=(size['''height'''], size['''width'''])			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					Any:
     return rescale(__A			,   scale=__A			,   data_format=__A			,   **__A						)


 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A			,   __A = None			,   **__A			,   ) ->					np.ndarray:
     return normalize(__A			,   mean=__A			,   std=__A			,   data_format=__A			,   **__A						)





 def 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = None			,   __A = ChannelDimension.FIRST			,   **__A			,   ) ->					PIL.Image.Image:
     a					=do_resize if do_resize is not None else self.do_resize
     a					=size if size is not None else self.size
     a					=get_size_dict(__A			,   param_name='''size'''			,   default_to_square=__A						)
     a					=resample if resample is not None else self.resample
     a					=do_center_crop if do_center_crop is not None else self.do_center_crop
     a					=crop_size if crop_size is not None else self.crop_size
     a					=get_size_dict(__A			,   param_name='''crop_size'''			,   default_to_square=__A						)
     a					=do_rescale if do_rescale is not None else self.do_rescale
     a					=rescale_factor if rescale_factor is not None else self.rescale_factor
     a					=do_normalize if do_normalize is not None else self.do_normalize
     a					=image_mean if image_mean is not None else self.image_mean
     a					=image_std if image_std is not None else self.image_std
     a					=do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

     a					=make_list_of_images(__A						)

     if not valid_images(__A						):
         raise ValueError(
             '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
             '''torch.Tensor, tf.Tensor or jax.ndarray.'''						)

     if do_resize and size is None:
         raise ValueError('''Size must be specified if do_resize is True.'''						)

     if do_center_crop and crop_size is None:
         raise ValueError('''Crop size must be specified if do_center_crop is True.'''						)

     if do_rescale and rescale_factor is None:
         raise ValueError('''Rescale factor must be specified if do_rescale is True.'''						)

     if do_normalize and (image_mean is None or image_std is None):
         raise ValueError('''Image mean and std must be specified if do_normalize is True.'''						)

     # PIL RGBA images are converted to RGB
     if do_convert_rgb:
         a					=[convert_to_rgb(__A						) for image in images]

     # All transformations expect numpy arrays.
     a					=[to_numpy_array(__A						) for image in images]

     if do_resize:
         a					=[self.resize(image=__A			,   size=__A			,   resample=__A						) for image in images]

     if do_center_crop:
         a					=[self.center_crop(image=__A			,   size=__A						) for image in images]

     if do_rescale:
         a					=[self.rescale(image=__A			,   scale=__A						) for image in images]

     if do_normalize:
         a					=[self.normalize(image=__A			,   mean=__A			,   std=__A						) for image in images]

     a					=[to_channel_dimension_format(__A			,   __A						) for image in images]

     a					={'''pixel_values''': images}
     return BatchFeature(data=__A			,   tensor_type=__A						)