


"""simple docstring"""







import argparse
import shutil
import time
from json import JSONDecodeError
from logging import getLogger
from pathlib import Path
from typing import Dict, List

import torch
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from utils import (
    SeqaSeqDataset,
    calculate_bleu,
    calculate_rouge,
    chunks,
    lmap,
    load_json,
    parse_numeric_n_bool_cl_kwargs,
    save_json,
    use_task_specific_params,
    write_txt_file,
)


a__       :							Dict        =  getLogger(__name__)




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_ = 8						,		lowerCAmelCase_ = 1024						,		lowerCAmelCase_="val"						,		lowerCAmelCase_=None						,		lowerCAmelCase_=False						,		lowerCAmelCase_="summarization"						,		lowerCAmelCase_=None						,		lowerCAmelCase_=1						,		lowerCAmelCase_ = None						,		lowerCAmelCase_=""						,		**lowerCAmelCase_						,		):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       str(lowerCAmelCase_     )
					assert local_rank is not None
					torch.distributed.init_process_group(backend="nccl"						,		rank=lowerCAmelCase_     )

					__SCREAMING_SNAKE_CASE		     =       Path(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       save_dir.joinpath(f"""rank_{local_rank}_output.json"""     )
					torch.cuda.set_device(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       AutoModelForSeqaSeqLM.from_pretrained(lowerCAmelCase_     ).cuda()
					if fpaa:
										__SCREAMING_SNAKE_CASE		     =       model.half()
					# determine if we need to increase num_beams
					use_task_specific_params(lowerCAmelCase_						,		lowerCAmelCase_     )  # update config with task specific params
					__SCREAMING_SNAKE_CASE		     =       generate_kwargs.pop("num_beams"						,		model.config.num_beams     )  # AttributeError risk?
					if num_return_sequences > num_beams:
										__SCREAMING_SNAKE_CASE		     =       num_return_sequences

					__SCREAMING_SNAKE_CASE		     =       AutoTokenizer.from_pretrained(lowerCAmelCase_     )
					logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}"""     )  # if this is wrong, check config.model_type.

					if max_source_length is None:
										__SCREAMING_SNAKE_CASE		     =       tokenizer.model_max_length
					if prefix is None:
										__SCREAMING_SNAKE_CASE		     =       prefix or getattr(model.config						,		"prefix"						,		""     ) or ""
					__SCREAMING_SNAKE_CASE		     =       SeqaSeqDataset(
					    lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		max_target_length=1024						,		type_path=lowerCAmelCase_						,		n_obs=lowerCAmelCase_						,		prefix=lowerCAmelCase_						,		**lowerCAmelCase_						,		)
					# I set shuffle=True for a more accurate progress bar.
					# If all the longest samples are first, the prog bar estimate is too high at the beginning.
					__SCREAMING_SNAKE_CASE		     =       ds.make_sortish_sampler(lowerCAmelCase_						,		distributed=lowerCAmelCase_						,		add_extra_examples=lowerCAmelCase_						,		shuffle=lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       DataLoader(lowerCAmelCase_						,		sampler=lowerCAmelCase_						,		batch_size=lowerCAmelCase_						,		collate_fn=ds.collate_fn     )
					__SCREAMING_SNAKE_CASE		     =       []
					for batch in tqdm(lowerCAmelCase_     ):
										__SCREAMING_SNAKE_CASE		     =       model.generate(
										    input_ids=batch["input_ids"].to(model.device     )						,		attention_mask=batch["attention_mask"].to(model.device     )						,		num_return_sequences=lowerCAmelCase_						,		num_beams=lowerCAmelCase_						,		**lowerCAmelCase_						,		)
										__SCREAMING_SNAKE_CASE		     =       tokenizer.batch_decode(lowerCAmelCase_						,		skip_special_tokens=lowerCAmelCase_						,		clean_up_tokenization_spaces=lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       batch["ids"]
										if num_return_sequences > 1:
															__SCREAMING_SNAKE_CASE		     =       chunks(lowerCAmelCase_						,		lowerCAmelCase_     )  # batch size chunks, each of size num_return_seq
										for i, pred in enumerate(lowerCAmelCase_     ):
															results.append({"pred": pred, "id": ids[i].item()}     )
					save_json(lowerCAmelCase_						,		lowerCAmelCase_     )
					return results, sampler.num_replicas




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       argparse.ArgumentParser(
					    epilog="Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate"     )
					parser.add_argument("--data_dir"						,		type=lowerCAmelCase_						,		help="like cnn_dm/test.source"     )
					parser.add_argument(
					    "--model_name"						,		type=lowerCAmelCase_						,		help="like facebook/bart-large-cnn,t5-base, etc."						,		default="sshleifer/distilbart-xsum-12-3"						,		)
					parser.add_argument("--save_dir"						,		type=lowerCAmelCase_						,		help="where to save"						,		default="tmp_gen"     )
					parser.add_argument("--max_source_length"						,		type=lowerCAmelCase_						,		default=lowerCAmelCase_     )
					parser.add_argument(
					    "--type_path"						,		type=lowerCAmelCase_						,		default="test"						,		help="which subset to evaluate typically train/val/test"     )
					parser.add_argument("--task"						,		type=lowerCAmelCase_						,		default="summarization"						,		help="used for task_specific_params + metrics"     )
					parser.add_argument("--bs"						,		type=lowerCAmelCase_						,		default=8						,		required=lowerCAmelCase_						,		help="batch size"     )
					parser.add_argument(
					    "--local_rank"						,		type=lowerCAmelCase_						,		default=-1						,		required=lowerCAmelCase_						,		help="should be passed by distributed.launch"     )

					parser.add_argument(
					    "--n_obs"						,		type=lowerCAmelCase_						,		default=lowerCAmelCase_						,		required=lowerCAmelCase_						,		help="How many observations. Defaults to all."     )
					parser.add_argument(
					    "--num_return_sequences"						,		type=lowerCAmelCase_						,		default=1						,		required=lowerCAmelCase_						,		help="How many sequences to return"     )
					parser.add_argument(
					    "--sync_timeout"						,		type=lowerCAmelCase_						,		default=600						,		required=lowerCAmelCase_						,		help="How long should master process wait for other processes to finish."						,		)
					parser.add_argument("--src_lang"						,		type=lowerCAmelCase_						,		default=lowerCAmelCase_						,		required=lowerCAmelCase_     )
					parser.add_argument("--tgt_lang"						,		type=lowerCAmelCase_						,		default=lowerCAmelCase_						,		required=lowerCAmelCase_     )
					parser.add_argument(
					    "--prefix"						,		type=lowerCAmelCase_						,		required=lowerCAmelCase_						,		default=lowerCAmelCase_						,		help="will be added to the begininng of src examples"     )
					parser.add_argument("--fp16"						,		action="store_true"     )
					parser.add_argument("--debug"						,		action="store_true"     )
					__SCREAMING_SNAKE_CASE		     =       time.time()
					__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       parser.parse_known_args()
					__SCREAMING_SNAKE_CASE		     =       parse_numeric_n_bool_cl_kwargs(lowerCAmelCase_     )
					if generate_kwargs and args.local_rank <= 0:
										print(f"""parsed the following generate kwargs: {generate_kwargs}"""     )
					__SCREAMING_SNAKE_CASE		     =       Path(args.save_dir + "_tmp"     )
					Path(lowerCAmelCase_     ).mkdir(exist_ok=lowerCAmelCase_     )  # this handles locking.
					__SCREAMING_SNAKE_CASE		     =       list(json_save_dir.glob("rank_*.json"     )     )
					if intermediate_files:
										raise ValueError(f"""Found files at {json_save_dir} please move or remove them."""     )
										# In theory, a node could finish and save before another node hits this. If this happens, we can address later.
					__SCREAMING_SNAKE_CASE		     =       {}
					if args.src_lang is not None:
										__SCREAMING_SNAKE_CASE		     =       args.src_lang
					if args.tgt_lang is not None:
										__SCREAMING_SNAKE_CASE		     =       args.tgt_lang

					Path(args.save_dir     ).mkdir(exist_ok=lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       eval_data_dir(
					    args.data_dir						,		lowerCAmelCase_						,		args.model_name						,		type_path=args.type_path						,		bs=args.bs						,		fpaa=args.fpaa						,		task=args.task						,		local_rank=args.local_rank						,		n_obs=args.n_obs						,		max_source_length=args.max_source_length						,		num_return_sequences=args.num_return_sequences						,		prefix=args.prefix						,		dataset_kwargs=lowerCAmelCase_						,		**lowerCAmelCase_						,		)

					if args.local_rank <= 0:
										__SCREAMING_SNAKE_CASE		     =       Path(args.save_dir     )
										save_dir.mkdir(exist_ok=lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       gather_results_from_each_node(lowerCAmelCase_						,		lowerCAmelCase_						,		args.sync_timeout     )
										__SCREAMING_SNAKE_CASE		     =       combine_partial_results(lowerCAmelCase_     )
										if args.num_return_sequences > 1:
															__SCREAMING_SNAKE_CASE		     =       save_dir.joinpath("pseudolabel_results.json"     )
															print(f"""Saving aggregated results at {save_path}, intermediate in {json_save_dir}/"""     )
															save_json(lowerCAmelCase_						,		lowerCAmelCase_     )
															return
										__SCREAMING_SNAKE_CASE		     =       Path(args.data_dir     ).joinpath(args.type_path + ".target"     )
										with open(lowerCAmelCase_     ) as f:
															__SCREAMING_SNAKE_CASE		     =       [x.rstrip() for x in f.readlines()][: len(lowerCAmelCase_     )]

										# Calculate metrics, save metrics,  and save _generations.txt
										__SCREAMING_SNAKE_CASE		     =       "translation" in args.task
										__SCREAMING_SNAKE_CASE		     =       calculate_bleu if calc_bleu else calculate_rouge
										__SCREAMING_SNAKE_CASE		     =       "bleu" if calc_bleu else "rouge"
										__SCREAMING_SNAKE_CASE		     =       score_fn(lowerCAmelCase_						,		lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       len(lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       time.time() - start_time
										__SCREAMING_SNAKE_CASE		     =       round(runtime / metrics["n_obs"]						,		4     )
										__SCREAMING_SNAKE_CASE		     =       num_replicas
										# TODO(@stas00): add whatever metadata to metrics
										__SCREAMING_SNAKE_CASE		     =       save_dir.joinpath(f"""{args.type_path}_{metric_name}.json"""     )
										save_json(lowerCAmelCase_						,		lowerCAmelCase_						,		indent=lowerCAmelCase_     )
										print(lowerCAmelCase_     )
										write_txt_file(lowerCAmelCase_						,		save_dir.joinpath(f"""{args.type_path}_generations.txt"""     )     )
										if args.debug:
															write_txt_file(lowerCAmelCase_						,		save_dir.joinpath(f"""{args.type_path}.target"""     )     )
										else:
															shutil.rmtree(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       []
					for partial_result in partial_results:
										records.extend(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       sorted(lowerCAmelCase_						,		key=lambda lowerCAmelCase_     : x["id"]     )
					__SCREAMING_SNAKE_CASE		     =       [x["pred"] for x in records]
					return preds




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       time.time()
					logger.info("waiting for all nodes to finish"     )
					__SCREAMING_SNAKE_CASE		     =       None
					while (time.time() - start_wait) < timeout:
										__SCREAMING_SNAKE_CASE		     =       list(save_dir.glob("rank_*.json"     )     )
										if len(lowerCAmelCase_     ) < num_replicas:
															continue
										try:
															# make sure all json files are fully saved
															__SCREAMING_SNAKE_CASE		     =       lmap(lowerCAmelCase_						,		lowerCAmelCase_     )
															return json_data
										except JSONDecodeError:
															continue
					else:
										raise TimeoutError("Rank 0 gave up on waiting for other processes"     )
					# Unreachable


if __name__ == "__main__":
	# Usage for MT:
	run_generate()




"""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''')

a__       :							str        =  logging.getLogger(__name__)




@dataclass
class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						str					      =    field(
	    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"})
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Pretrained config name or path if not the same as model_name"})
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"})
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}    ,						)
	snake_case__       :						str					      =    field(
	    default="main"    ,						metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": (
	            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
	            "with private models)."
	        )
	    }    ,						)




@dataclass
class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						Optional[str]					      =    field(default=UpperCamelCase    ,						metadata={"help": "The input training data file (a text file)."})
	snake_case__       :						Optional[str]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "Overwrite the cached training and evaluation sets"})
	snake_case__       :						Optional[int]					      =    field(
	    default=UpperCamelCase    ,						metadata={"help": "The number of processes to use for the preprocessing."}    ,						)
	snake_case__       :						Optional[int]					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": (
	            "The maximum total input sequence length after tokenization. If passed, sequences longer "
	            "than this will be truncated, sequences shorter will be padded."
	        )
	    }    ,						)
	snake_case__       :						bool					      =    field(
	    default=UpperCamelCase    ,						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."
	        )
	    }    ,						)
	snake_case__       :						Optional[int]					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of training examples to this "
	            "value if set."
	        )
	    }    ,						)
	snake_case__       :						Optional[int]					      =    field(
	    default=UpperCamelCase    ,						metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
	            "value if set."
	        )
	    }    ,						)




	def 						UpperCAmelCase_   (				self    :       Any     ) ->			Optional[int]:
						if self.train_file is not None:
											__SCREAMING_SNAKE_CASE		     =       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:
											__SCREAMING_SNAKE_CASE		     =       self.validation_file.split("."     )[-1]
											assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."




@dataclass
class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						PreTrainedTokenizerBase
	snake_case__       :						Union[bool, str, PaddingStrategy]					      =    True
	snake_case__       :						Optional[int]					      =    None
	snake_case__       :						Optional[int]					      =    None




	def __call__(				self    :       Dict    ,    UpperCAmelCase__    :       Dict     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       "label" if "label" in features[0].keys() else "labels"
						__SCREAMING_SNAKE_CASE		     =       [feature.pop(UpperCAmelCase__     ) for feature in features]
						__SCREAMING_SNAKE_CASE		     =       len(UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       len(features[0]["input_ids"]     )
						__SCREAMING_SNAKE_CASE		     =       [
						    [{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase__     )] for feature in features
						]
						__SCREAMING_SNAKE_CASE		     =       list(chain(*UpperCAmelCase__     )     )

						__SCREAMING_SNAKE_CASE		     =       self.tokenizer.pad(
						    UpperCAmelCase__    ,    padding=self.padding    ,    max_length=self.max_length    ,    pad_to_multiple_of=self.pad_to_multiple_of    ,    return_tensors="pt"    ,    )

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




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       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.
										__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
					else:
										__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       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"						,		lowerCAmelCase_						,		lowerCAmelCase_     )

					# 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()

					__SCREAMING_SNAKE_CASE		     =       training_args.get_process_log_level()
					logger.setLevel(lowerCAmelCase_     )
					datasets.utils.logging.set_verbosity(lowerCAmelCase_     )
					transformers.utils.logging.set_verbosity(lowerCAmelCase_     )
					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.
					__SCREAMING_SNAKE_CASE		     =       None
					if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
										__SCREAMING_SNAKE_CASE		     =       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:
										__SCREAMING_SNAKE_CASE		     =       {}
										if data_args.train_file is not None:
															__SCREAMING_SNAKE_CASE		     =       data_args.train_file
										if data_args.validation_file is not None:
															__SCREAMING_SNAKE_CASE		     =       data_args.validation_file
										__SCREAMING_SNAKE_CASE		     =       data_args.train_file.split("."     )[-1]
										__SCREAMING_SNAKE_CASE		     =       load_dataset(
										    lowerCAmelCase_						,		data_files=lowerCAmelCase_						,		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.
										__SCREAMING_SNAKE_CASE		     =       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.
					__SCREAMING_SNAKE_CASE		     =       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						,		)
					__SCREAMING_SNAKE_CASE		     =       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						,		)
					__SCREAMING_SNAKE_CASE		     =       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						,		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.
					__SCREAMING_SNAKE_CASE		     =       [f"""ending{i}""" for i in range(4     )]
					__SCREAMING_SNAKE_CASE		     =       "sent1"
					__SCREAMING_SNAKE_CASE		     =       "sent2"

					if data_args.max_seq_length is None:
										__SCREAMING_SNAKE_CASE		     =       tokenizer.model_max_length
										if max_seq_length > 1024:
															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`."     )
															__SCREAMING_SNAKE_CASE		     =       1024
					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}."""     )
										__SCREAMING_SNAKE_CASE		     =       min(data_args.max_seq_length						,		tokenizer.model_max_length     )

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

										# Flatten out
										__SCREAMING_SNAKE_CASE		     =       list(chain(*lowerCAmelCase_     )     )
										__SCREAMING_SNAKE_CASE		     =       list(chain(*lowerCAmelCase_     )     )

										# Tokenize
										__SCREAMING_SNAKE_CASE		     =       tokenizer(
										    lowerCAmelCase_						,		lowerCAmelCase_						,		truncation=lowerCAmelCase_						,		max_length=lowerCAmelCase_						,		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(lowerCAmelCase_     )						,		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"     )
										__SCREAMING_SNAKE_CASE		     =       raw_datasets["train"]
										if data_args.max_train_samples is not None:
															__SCREAMING_SNAKE_CASE		     =       min(len(lowerCAmelCase_     )						,		data_args.max_train_samples     )
															__SCREAMING_SNAKE_CASE		     =       train_dataset.select(range(lowerCAmelCase_     )     )
										with training_args.main_process_first(desc="train dataset map pre-processing"     ):
															__SCREAMING_SNAKE_CASE		     =       train_dataset.map(
															    lowerCAmelCase_						,		batched=lowerCAmelCase_						,		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"     )
										__SCREAMING_SNAKE_CASE		     =       raw_datasets["validation"]
										if data_args.max_eval_samples is not None:
															__SCREAMING_SNAKE_CASE		     =       min(len(lowerCAmelCase_     )						,		data_args.max_eval_samples     )
															__SCREAMING_SNAKE_CASE		     =       eval_dataset.select(range(lowerCAmelCase_     )     )
										with training_args.main_process_first(desc="validation dataset map pre-processing"     ):
															__SCREAMING_SNAKE_CASE		     =       eval_dataset.map(
															    lowerCAmelCase_						,		batched=lowerCAmelCase_						,		num_proc=data_args.preprocessing_num_workers						,		load_from_cache_file=not data_args.overwrite_cache						,		)

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

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

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

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

										__SCREAMING_SNAKE_CASE		     =       (
										    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_     )
										)
										__SCREAMING_SNAKE_CASE		     =       min(lowerCAmelCase_						,		len(lowerCAmelCase_     )     )

										trainer.log_metrics("train"						,		lowerCAmelCase_     )
										trainer.save_metrics("train"						,		lowerCAmelCase_     )
										trainer.save_state()

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

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

										trainer.log_metrics("eval"						,		lowerCAmelCase_     )
										trainer.save_metrics("eval"						,		lowerCAmelCase_     )

					__SCREAMING_SNAKE_CASE		     =       {
					    "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(**lowerCAmelCase_     )
					else:
										trainer.create_model_card(**lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					main()


if __name__ == "__main__":
		main()
