





import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


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

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''')

UpperCAmelCase__  :     str   			=logging.getLogger(__name__)

@dataclass
class  __A       :
				__A								=			field(
				    default=1_28      ,   metadata={
				        """help""": (
				            """The maximum total input sequence length after tokenization. Sequences longer """
				            """than this will be truncated, sequences shorter will be padded."""
				        )
				    }      ,   )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}      )
				__A								=			field(
				    default=a      ,   metadata={
				        """help""": (
				            """Whether to pad all samples to `max_seq_length`. """
				            """If False, will pad the samples dynamically when batching to the maximum length in the batch."""
				        )
				    }      ,   )
				__A								=			field(
				    default=a      ,   metadata={
				        """help""": (
				            """For debugging purposes or quicker training, truncate the number of training examples to this """
				            """value if set."""
				        )
				    }      ,   )
				__A								=			field(
				    default=a      ,   metadata={
				        """help""": (
				            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
				            """value if set."""
				        )
				    }      ,   )
				__A								=			field(
				    default=a      ,   metadata={
				        """help""": (
				            """For debugging purposes or quicker training, truncate the number of prediction examples to this """
				            """value if set."""
				        )
				    }      ,   )




@dataclass
class  __A       :
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}      )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""}      )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Train language if it is different from the evaluation language."""}      )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}      )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}      )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}      ,   )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""}      ,   )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}      ,   )
				__A								=			field(
				    default="""main"""      ,   metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}      ,   )
				__A								=			field(
				    default=a      ,   metadata={
				        """help""": (
				            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
				            """with private models)."""
				        )
				    }      ,   )
				__A								=			field(
				    default=a      ,   metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}      ,   )





def        _lowercase   (  )  ->					int:
				# See all possible arguments in src/transformers/training_args.py
				# or by passing the --help flag to this script.
				# We now keep distinct sets of args, for a cleaner separation of concerns.

				lowerCamelCase			=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
				lowerCamelCase	,					lowerCamelCase	,					lowerCamelCase			=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_xnli"""     , _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()

				lowerCamelCase			=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.
				lowerCamelCase			=None
				if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
								lowerCamelCase			=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:
												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			)

				# In distributed training, the load_dataset function guarantees that only one local process can concurrently
				# download the dataset.
				# Downloading and loading xnli dataset from the hub.
				if training_args.do_train:
								if model_args.train_language is None:
												lowerCamelCase			=load_dataset(
												    """xnli"""     , model_args.language     , split="""train"""     , cache_dir=model_args.cache_dir     , use_auth_token=True if model_args.use_auth_token else None     , )
								else:
												lowerCamelCase			=load_dataset(
												    """xnli"""     , model_args.train_language     , split="""train"""     , cache_dir=model_args.cache_dir     , use_auth_token=True if model_args.use_auth_token else None     , )
								lowerCamelCase			=train_dataset.features["""label"""].names

				if training_args.do_eval:
								lowerCamelCase			=load_dataset(
								    """xnli"""     , model_args.language     , split="""validation"""     , cache_dir=model_args.cache_dir     , use_auth_token=True if model_args.use_auth_token else None     , )
								lowerCamelCase			=eval_dataset.features["""label"""].names

				if training_args.do_predict:
								lowerCamelCase			=load_dataset(
								    """xnli"""     , model_args.language     , split="""test"""     , cache_dir=model_args.cache_dir     , use_auth_token=True if model_args.use_auth_token else None     , )
								lowerCamelCase			=predict_dataset.features["""label"""].names

				# Labels
				lowerCamelCase			=len(_UpperCAmelCase			)

				# Load pretrained model and tokenizer
				# In 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=_UpperCAmelCase     , idalabel={str(_UpperCAmelCase			): label for i, label in enumerate(_UpperCAmelCase			)}     , labelaid={label: i for i, label in enumerate(_UpperCAmelCase			)}     , finetuning_task="""xnli"""     , cache_dir=model_args.cache_dir     , revision=model_args.model_revision     , use_auth_token=True if model_args.use_auth_token else None     , )
				lowerCamelCase			=AutoTokenizer.from_pretrained(
				    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path     , do_lower_case=model_args.do_lower_case     , 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     , )
				lowerCamelCase			=AutoModelForSequenceClassification.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     , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes     , )

				# Preprocessing the datasets
				# Padding strategy
				if data_args.pad_to_max_length:
								lowerCamelCase			="""max_length"""
				else:
								# We will pad later, dynamically at batch creation, to the max sequence length in each batch
								lowerCamelCase			=False

				def preprocess_function(_UpperCAmelCase			):
								# Tokenize the texts
								return tokenizer(
								    examples["""premise"""]     , examples["""hypothesis"""]     , padding=_UpperCAmelCase     , max_length=data_args.max_seq_length     , truncation=_UpperCAmelCase     , )

				if training_args.do_train:
								if data_args.max_train_samples is not None:
												lowerCamelCase			=min(len(_UpperCAmelCase			)     , data_args.max_train_samples			)
												lowerCamelCase			=train_dataset.select(range(_UpperCAmelCase			)			)
								with training_args.main_process_first(desc="""train dataset map pre-processing"""			):
												lowerCamelCase			=train_dataset.map(
												    _UpperCAmelCase     , batched=_UpperCAmelCase     , load_from_cache_file=not data_args.overwrite_cache     , desc="""Running tokenizer on train dataset"""     , )
								# Log a few random samples from the training set:
								for index in random.sample(range(len(_UpperCAmelCase			)			)     , 3			):
												logger.info(F"""Sample {index} of the training set: {train_dataset[index]}."""			)

				if training_args.do_eval:
								if data_args.max_eval_samples is not None:
												lowerCamelCase			=min(len(_UpperCAmelCase			)     , data_args.max_eval_samples			)
												lowerCamelCase			=eval_dataset.select(range(_UpperCAmelCase			)			)
								with training_args.main_process_first(desc="""validation dataset map pre-processing"""			):
												lowerCamelCase			=eval_dataset.map(
												    _UpperCAmelCase     , batched=_UpperCAmelCase     , load_from_cache_file=not data_args.overwrite_cache     , desc="""Running tokenizer on validation dataset"""     , )

				if training_args.do_predict:
								if data_args.max_predict_samples is not None:
												lowerCamelCase			=min(len(_UpperCAmelCase			)     , data_args.max_predict_samples			)
												lowerCamelCase			=predict_dataset.select(range(_UpperCAmelCase			)			)
								with training_args.main_process_first(desc="""prediction dataset map pre-processing"""			):
												lowerCamelCase			=predict_dataset.map(
												    _UpperCAmelCase     , batched=_UpperCAmelCase     , load_from_cache_file=not data_args.overwrite_cache     , desc="""Running tokenizer on prediction dataset"""     , )

    # Get the metric function
				lowerCamelCase			=evaluate.load("""xnli"""			)

				# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
				# predictions and label_ids field) and has to return a dictionary string to float.
				def compute_metrics(_UpperCAmelCase			):
								lowerCamelCase			=p.predictions[0] if isinstance(p.predictions     , _UpperCAmelCase			) else p.predictions
								lowerCamelCase			=np.argmax(_UpperCAmelCase     , axis=1			)
								return metric.compute(predictions=_UpperCAmelCase     , references=p.label_ids			)

				# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
				if data_args.pad_to_max_length:
								lowerCamelCase			=default_data_collator
				elif training_args.fpaa:
								lowerCamelCase			=DataCollatorWithPadding(_UpperCAmelCase     , pad_to_multiple_of=8			)
				else:
								lowerCamelCase			=None

				# Initialize our Trainer
				lowerCamelCase			=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     , compute_metrics=_UpperCAmelCase     , tokenizer=_UpperCAmelCase     , data_collator=_UpperCAmelCase     , )

				# Training
				if training_args.do_train:
								lowerCamelCase			=None
								if training_args.resume_from_checkpoint is not None:
												lowerCamelCase			=training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												lowerCamelCase			=last_checkpoint
								lowerCamelCase			=trainer.train(resume_from_checkpoint=_UpperCAmelCase			)
								lowerCamelCase			=train_result.metrics
								lowerCamelCase			=(
								    data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCAmelCase			)
								)
								lowerCamelCase			=min(_UpperCAmelCase     , len(_UpperCAmelCase			)			)

								trainer.save_model()  # Saves the tokenizer too for easy upload

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

				# Evaluation
				if training_args.do_eval:
								logger.info("""*** Evaluate ***"""			)
								lowerCamelCase			=trainer.evaluate(eval_dataset=_UpperCAmelCase			)

								lowerCamelCase			=data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_UpperCAmelCase			)
								lowerCamelCase			=min(_UpperCAmelCase     , len(_UpperCAmelCase			)			)

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

				# Prediction
				if training_args.do_predict:
								logger.info("""*** Predict ***"""			)
								lowerCamelCase	,					lowerCamelCase	,					lowerCamelCase			=trainer.predict(_UpperCAmelCase     , metric_key_prefix="""predict"""			)

								lowerCamelCase			=(
								    data_args.max_predict_samples if data_args.max_predict_samples is not None else len(_UpperCAmelCase			)
								)
								lowerCamelCase			=min(_UpperCAmelCase     , len(_UpperCAmelCase			)			)

								trainer.log_metrics("""predict"""     , _UpperCAmelCase			)
								trainer.save_metrics("""predict"""     , _UpperCAmelCase			)

								lowerCamelCase			=np.argmax(_UpperCAmelCase     , axis=1			)
								lowerCamelCase			=os.path.join(training_args.output_dir     , """predictions.txt"""			)
								if trainer.is_world_process_zero():
												with open(_UpperCAmelCase     , """w"""			) as writer:
																writer.write("""index\tprediction\n"""			)
																for index, item in enumerate(_UpperCAmelCase			):
																				lowerCamelCase			=label_list[item]
																				writer.write(F"""{index}\t{item}\n"""			)


if __name__ == "__main__":
							main()













import argparse
import os
import re

import packaging.version


UpperCAmelCase__  :     List[Any]   			='''examples/'''
UpperCAmelCase__  :     List[str]   			={
    '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''),
    '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
UpperCAmelCase__  :     List[Any]   			={
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
UpperCAmelCase__  :     Union[str, Any]   			='''README.md'''





def        _lowercase   (  _UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase			)  ->					str:
				with open(_UpperCAmelCase     , """r"""     , encoding="""utf-8"""     , newline="""\n"""			) as f:
								lowerCamelCase			=f.read()
				lowerCamelCase	,					lowerCamelCase			=REPLACE_PATTERNS[pattern]
				lowerCamelCase			=replace.replace("""VERSION"""     , _UpperCAmelCase			)
				lowerCamelCase			=re_pattern.sub(_UpperCAmelCase     , _UpperCAmelCase			)
				with open(_UpperCAmelCase     , """w"""     , encoding="""utf-8"""     , newline="""\n"""			) as f:
								f.write(_UpperCAmelCase			)





def        _lowercase   (  _UpperCAmelCase			)  ->					int:
				for folder, directories, fnames in os.walk(_UpperCAmelCase			):
								# Removing some of the folders with non-actively maintained examples from the walk
								if "research_projects" in directories:
												directories.remove("""research_projects"""			)
								if "legacy" in directories:
												directories.remove("""legacy"""			)
								for fname in fnames:
												if fname.endswith(""".py"""			):
																update_version_in_file(os.path.join(_UpperCAmelCase     , _UpperCAmelCase			)     , _UpperCAmelCase     , pattern="""examples"""			)





def        _lowercase   (  _UpperCAmelCase     , _UpperCAmelCase=False			)  ->					Any:
				for pattern, fname in REPLACE_FILES.items():
								update_version_in_file(_UpperCAmelCase     , _UpperCAmelCase     , _UpperCAmelCase			)
				if not patch:
								update_version_in_examples(_UpperCAmelCase			)





def        _lowercase   (  )  ->					Dict:
				lowerCamelCase			="""🤗 Transformers currently provides the following architectures"""
				lowerCamelCase			="""1. Want to contribute a new model?"""
				with open(_UpperCAmelCase     , """r"""     , encoding="""utf-8"""     , newline="""\n"""			) as f:
								lowerCamelCase			=f.readlines()

				# Find the start of the list.
				lowerCamelCase			=0
				while not lines[start_index].startswith(_start_prompt			):
								start_index += 1
				start_index += 1

				lowerCamelCase			=start_index
				# Update the lines in the model list.
				while not lines[index].startswith(_end_prompt			):
								if lines[index].startswith("""1."""			):
												lowerCamelCase			=lines[index].replace(
												    """https://huggingface.co/docs/transformers/main/model_doc"""     , """https://huggingface.co/docs/transformers/model_doc"""     , )
								index += 1

				with open(_UpperCAmelCase     , """w"""     , encoding="""utf-8"""     , newline="""\n"""			) as f:
								f.writelines(_UpperCAmelCase			)





def        _lowercase   (  )  ->					Optional[int]:
				with open(REPLACE_FILES["""init"""]     , """r"""			) as f:
								lowerCamelCase			=f.read()
				lowerCamelCase			=REPLACE_PATTERNS["""init"""][0].search(_UpperCAmelCase			).groups()[0]
				return packaging.version.parse(_UpperCAmelCase			)





def        _lowercase   (  _UpperCAmelCase=False			)  ->					List[str]:
				lowerCamelCase			=get_version()
				if patch and default_version.is_devrelease:
								raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""			)
				if default_version.is_devrelease:
								lowerCamelCase			=default_version.base_version
				elif patch:
								lowerCamelCase			=F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
				else:
								lowerCamelCase			=F"""{default_version.major}.{default_version.minor + 1}.0"""

				# Now let's ask nicely if that's the right one.
				lowerCamelCase			=input(F"""Which version are you releasing? [{default_version}]"""			)
				if len(_UpperCAmelCase			) == 0:
								lowerCamelCase			=default_version

				print(F"""Updating version to {version}."""			)
				global_version_update(_UpperCAmelCase     , patch=_UpperCAmelCase			)
				if not patch:
								print("""Cleaning main README, don't forget to run `make fix-copies`."""			)
								clean_main_ref_in_model_list()





def        _lowercase   (  )  ->					str:
				lowerCamelCase			=get_version()
				lowerCamelCase			=F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
				lowerCamelCase			=current_version.base_version

				# Check with the user we got that right.
				lowerCamelCase			=input(F"""Which version are we developing now? [{dev_version}]"""			)
				if len(_UpperCAmelCase			) == 0:
								lowerCamelCase			=dev_version

				print(F"""Updating version to {version}."""			)
				global_version_update(_UpperCAmelCase			)
				print("""Cleaning main README, don't forget to run `make fix-copies`."""			)
				clean_main_ref_in_model_list()


if __name__ == "__main__":
							UpperCAmelCase__  :     Optional[Any]   			=argparse.ArgumentParser()
							parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
							parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
							UpperCAmelCase__  :     str   			=parser.parse_args()
							if not args.post_release:
														pre_release_work(patch=args.patch)
							elif args.patch:
														print('''Nothing to do after a patch :-)''')
							else:
														post_release_work()





