

import os
import zipfile

import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links



def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Optional[int]		,				SCREAMING_SNAKE_CASE_:							Union[str, Any]=7					)	->					str:




				'''simple docstring'''





				A__						=	None
				if token is not None:
								A__						=	{"Accept": "application/vnd.github+json", "Authorization": F'Bearer {token}'}

				# The id of a workflow (not of a workflow run)
				A__						=	"636036"

				A__						=	F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs'
				# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
				url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}'

				A__						=	requests.get(SCREAMING_SNAKE_CASE_		,				headers=SCREAMING_SNAKE_CASE_					).json()

				return result["workflow_runs"]



def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Optional[Any]					)	->					Optional[int]:




				'''simple docstring'''





				A__						=	get_daily_ci_runs(SCREAMING_SNAKE_CASE_					)
				A__						=	None
				for workflow_run in workflow_runs:
								if workflow_run["status"] == "completed":
												A__						=	workflow_run["id"]
												break

				return workflow_run_id



def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Tuple		,				SCREAMING_SNAKE_CASE_:							List[str]		,				SCREAMING_SNAKE_CASE_:							str					)	->					List[str]:




				'''simple docstring'''





				A__						=	get_last_daily_ci_runs(SCREAMING_SNAKE_CASE_					)
				if workflow_run_id is not None:
								A__						=	get_artifacts_links(worflow_run_id=SCREAMING_SNAKE_CASE_		,				token=SCREAMING_SNAKE_CASE_					)
								for artifact_name in artifact_names:
												if artifact_name in artifacts_links:
																A__						=	artifacts_links[artifact_name]
																download_artifact(
																    artifact_name=SCREAMING_SNAKE_CASE_		,				artifact_url=SCREAMING_SNAKE_CASE_		,				output_dir=SCREAMING_SNAKE_CASE_		,				token=SCREAMING_SNAKE_CASE_					)





def     lowerCAmelCase__							(		SCREAMING_SNAKE_CASE_:							Union[str, Any]		,				SCREAMING_SNAKE_CASE_:							Optional[int]		,				SCREAMING_SNAKE_CASE_:							List[str]					)	->					Optional[int]:




				'''simple docstring'''





				get_last_daily_ci_artifacts(SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_		,				SCREAMING_SNAKE_CASE_					)

				A__						=	{}
				for artifact_name in artifact_names:
								A__						=	os.path.join(SCREAMING_SNAKE_CASE_		,				F'{artifact_name}.zip'					)
								if os.path.isfile(SCREAMING_SNAKE_CASE_					):
												A__						=	{}
												with zipfile.ZipFile(SCREAMING_SNAKE_CASE_					) as z:
																for filename in z.namelist():
																				if not os.path.isdir(SCREAMING_SNAKE_CASE_					):
																								# read the file
																								with z.open(SCREAMING_SNAKE_CASE_					) as f:
																												A__						=	f.read().decode("UTF-8"					)

				return results








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				:    Optional[int]       =   logging.getLogger(__name__)

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

@dataclass
class 	A_       :
	UpperCAmelCase__					=			field(default=a_     ,							metadata={'''help''': '''The input training data file (a text file).'''}			)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}     ,							)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}			)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={'''help''': '''The number of processes to use for the preprocessing.'''}     ,							)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={
	        '''help''': (
	            '''The maximum total input sequence length after tokenization. If passed, sequences longer '''
	            '''than this will be truncated, sequences shorter will be padded.'''
	        )
	    }     ,							)
	UpperCAmelCase__					=			field(
	    default=a_     ,							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.'''
	        )
	    }     ,							)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={
	        '''help''': (
	            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
	            '''value if set.'''
	        )
	    }     ,							)
	UpperCAmelCase__					=			field(
	    default=a_     ,							metadata={
	        '''help''': (
	            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
	            '''value if set.'''
	        )
	    }     ,							)
	def      _lowercase				(    self		):






				'''simple docstring'''







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

@dataclass
class 	A_       :
	UpperCAmelCase__					=			42
	UpperCAmelCase__					=			True
	UpperCAmelCase__					=			None
	UpperCAmelCase__					=			None
	def __call__(    self							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				'''label''' if '''label''' in features[0].keys() else '''labels'''
				UpperCAmelCase   		=				[feature.pop(_A		) for feature in features]
				UpperCAmelCase   		=				len(_A		)
				UpperCAmelCase   		=				len(features[0]['''input_ids''']		)
				UpperCAmelCase   		=				[
				    [{k: v[i] for k, v in feature.items()} for i in range(_A		)] for feature in features
				]
				UpperCAmelCase   		=				list(chain(*_A		)		)

				UpperCAmelCase   		=				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
				UpperCAmelCase   		=				{k: v.view(_A							,					_A							,					-1		) for k, v in batch.items()}
				# Add back labels
				UpperCAmelCase   		=				torch.tensor(_A							,					dtype=torch.intaa		)
				return batch





def 						__SCREAMING_SNAKE_CASE  (				)  ->				Optional[int]:







			'''simple docstring'''

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

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

			UpperCAmelCase   		=				training_args.get_process_log_level()
			logger.setLevel(UpperCamelCase__ )
			datasets.utils.logging.set_verbosity(UpperCamelCase__ )
			transformers.utils.logging.set_verbosity(UpperCamelCase__ )
			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.
			UpperCAmelCase   		=				None
			if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
						UpperCAmelCase   		=				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:
						UpperCAmelCase   		=				{}
						if data_args.train_file is not None:
									UpperCAmelCase   		=				data_args.train_file
						if data_args.validation_file is not None:
									UpperCAmelCase   		=				data_args.validation_file
						UpperCAmelCase   		=				data_args.train_file.split('''.''' )[-1]
						UpperCAmelCase   		=				load_dataset(
						    UpperCamelCase__			,			data_files=UpperCamelCase__			,			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.
						UpperCAmelCase   		=				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.
			UpperCAmelCase   		=				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			,			)
			UpperCAmelCase   		=				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			,			)
			UpperCAmelCase   		=				AutoModelForMultipleChoice.from_pretrained(
			    model_args.model_name_or_path			,			from_tf=bool('''.ckpt''' in model_args.model_name_or_path )			,			config=UpperCamelCase__			,			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.
			UpperCAmelCase   		=				[F"""ending{i}""" for i in range(4 )]
			UpperCAmelCase   		=				'''sent1'''
			UpperCAmelCase   		=				'''sent2'''

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

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

						# Flatten out
						UpperCAmelCase   		=				list(chain(*UpperCamelCase__ ) )
						UpperCAmelCase   		=				list(chain(*UpperCamelCase__ ) )

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

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

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

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

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

						UpperCAmelCase   		=				(
						    data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCamelCase__ )
						)
						UpperCAmelCase   		=				min(UpperCamelCase__			,			len(UpperCamelCase__ ) )

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

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

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

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

			UpperCAmelCase   		=				{
			    '''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(**UpperCamelCase__ )
			else:
						trainer.create_model_card(**UpperCamelCase__ )





def 						__SCREAMING_SNAKE_CASE  (				UpperCamelCase__ )  ->				int:







			'''simple docstring'''

			main()


if __name__ == "__main__":
				main()



