



"""simple docstring"""







import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase_   						=   version.parse(importlib_metadata.version('nltk'))
if NLTK_VERSION >= version.Version('3.6.4'):
							from nltk import word_tokenize


lowerCAmelCase_   						=   '\\n@inproceedings{banarjee2005,\n  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n  author    = {Banerjee, Satanjeev  and Lavie, Alon},\n  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n  month     = jun,\n  year      = {2005},\n  address   = {Ann Arbor, Michigan},\n  publisher = {Association for Computational Linguistics},\n  url       = {https://www.aclweb.org/anthology/W05-0909},\n  pages     = {65--72},\n}\n'

lowerCAmelCase_   						=   '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n'

lowerCAmelCase_   						=   '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n    gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n    \'meteor\': meteor score.\nExamples:\n\n    >>> meteor = datasets.load_metric(\'meteor\')\n    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n    >>> results = meteor.compute(predictions=predictions, references=references)\n    >>> print(round(results["meteor"], 4))\n    0.6944\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,_KWARGS_DESCRIPTION    )
class        __A       (	datasets.Metric    ):







		'''simple docstring'''





		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		str:






				"""simple docstring"""



				return datasets.MetricInfo(
				    description=_DESCRIPTION			,citation=_CITATION			,inputs_description=_KWARGS_DESCRIPTION			,features=datasets.Features(
				        {
				            '''predictions''': datasets.Value('''string'''			,id='''sequence'''						),
				            '''references''': datasets.Value('''string'''			,id='''sequence'''						),
				        }						)			,codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py''']			,reference_urls=[
				        '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''',
				        '''https://en.wikipedia.org/wiki/METEOR''',
				    ]			,)







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  Dict						)					->		Dict:






				"""simple docstring"""



				import nltk

				nltk.download('''wordnet'''						)
				if NLTK_VERSION >= version.Version('''3.6.5'''						):
						nltk.download('''punkt'''						)
				if NLTK_VERSION >= version.Version('''3.6.6'''						):
						nltk.download('''omw-1.4'''						)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Tuple=0.9			,_snake_case						:  Optional[int]=3			,_snake_case						:  Union[str, Any]=0.5						)					->		List[str]:






				"""simple docstring"""



				if NLTK_VERSION >= version.Version('''3.6.5'''						):
						lowercase__   :    int				=			[
						    meteor_score.single_meteor_score(
						        word_tokenize(_snake_case						)			,word_tokenize(_snake_case						)			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]
				else:
						lowercase__   :    Tuple				=			[
						    meteor_score.single_meteor_score(_snake_case			,_snake_case			,alpha=_snake_case			,beta=_snake_case			,gamma=_snake_case						)
						    for ref, pred in zip(_snake_case			,_snake_case						)
						]

				return {"meteor": np.mean(_snake_case						)}





"""simple docstring"""







import argparse
import os

# New Code #
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.utils import find_executable_batch_size


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to ensure out-of-memory errors never
# interrupt training, and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


lowerCAmelCase_   						=   16
lowerCAmelCase_   						=   32



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase = 16	)							->      Optional[Any]:
		lowercase__   :    Optional[Any]				=			AutoTokenizer.from_pretrained('''bert-base-cased'''	)
		lowercase__   :    int				=			load_dataset('''glue'''						,     '''mrpc'''	)

		def tokenize_function(__lowerCamelCase	):
				# max_length=None => use the model max length (it's actually the default)
				lowercase__   :    str				=			tokenizer(examples['''sentence1''']						,     examples['''sentence2''']						,     truncation=__lowerCamelCase						,     max_length=__lowerCamelCase	)
				return outputs

		# Apply the method we just defined to all the examples in all the splits of the dataset
		# starting with the main process first:
		with accelerator.main_process_first():
				lowercase__   :    str				=			datasets.map(
				    __lowerCamelCase						,     batched=__lowerCamelCase						,     remove_columns=['''idx''', '''sentence1''', '''sentence2''']						,     )

		# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
		# transformers library
		lowercase__   :    Union[str, Any]				=			tokenized_datasets.rename_column('''label'''						,     '''labels'''	)

		def collate_fn(__lowerCamelCase	):
				# On TPU it's best to pad everything to the same length or training will be very slow.
				lowercase__   :    List[str]				=			1_28 if accelerator.distributed_type == DistributedType.TPU else None
				# When using mixed precision we want round multiples of 8/16
				if accelerator.mixed_precision == "fp8":
						lowercase__   :    Optional[int]				=			16
				elif accelerator.mixed_precision != "no":
						lowercase__   :    List[Any]				=			8
				else:
						lowercase__   :    int				=			None

				return tokenizer.pad(
				    __lowerCamelCase						,     padding='''longest'''						,     max_length=__lowerCamelCase						,     pad_to_multiple_of=__lowerCamelCase						,     return_tensors='''pt'''						,     )

		# Instantiate dataloaders.
		lowercase__   :    List[Any]				=			DataLoader(
		    tokenized_datasets['''train''']						,     shuffle=__lowerCamelCase						,     collate_fn=__lowerCamelCase						,     batch_size=__lowerCamelCase	)
		lowercase__   :    str				=			DataLoader(
		    tokenized_datasets['''validation''']						,     shuffle=__lowerCamelCase						,     collate_fn=__lowerCamelCase						,     batch_size=__lowerCamelCase	)

		return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
							from accelerate.test_utils.training import mocked_dataloaders

							lowerCAmelCase_   						=   mocked_dataloaders  # noqa: F811



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase	)							->      str:
		# For testing only
		if os.environ.get('''TESTING_MOCKED_DATALOADERS'''						,     __lowerCamelCase	) == "1":
				lowercase__   :    List[Any]				=			2
		# Initialize accelerator
		lowercase__   :    Optional[int]				=			Accelerator(cpu=args.cpu						,     mixed_precision=args.mixed_precision	)
		# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
		lowercase__   :    str				=			config['''lr''']
		lowercase__   :    str				=			int(config['''num_epochs''']	)
		lowercase__   :    Optional[int]				=			int(config['''seed''']	)
		lowercase__   :    Tuple				=			int(config['''batch_size''']	)

		lowercase__   :    List[Any]				=			evaluate.load('''glue'''						,     '''mrpc'''	)

		# New Code #
		# We now can define an inner training loop function. It should take a batch size as the only parameter,
		# and build the dataloaders in there.
		# It also gets our decorator
		@find_executable_batch_size(starting_batch_size=__lowerCamelCase	)
		def inner_training_loop(__lowerCamelCase	):
				# And now just move everything below under this function
				# We need to bring in the Accelerator object from earlier
				nonlocal accelerator
				# And reset all of its attributes that could hold onto any memory:
				accelerator.free_memory()

				# Then we can declare the model, optimizer, and everything else:
				set_seed(__lowerCamelCase	)

				# Instantiate the model (we build the model here so that the seed also control new weights initialization)
				lowercase__   :    List[str]				=			AutoModelForSequenceClassification.from_pretrained('''bert-base-cased'''						,     return_dict=__lowerCamelCase	)

				# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
				# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
				# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
				lowercase__   :    Tuple				=			model.to(accelerator.device	)

				# Instantiate optimizer
				lowercase__   :    List[str]				=			AdamW(params=model.parameters()						,     lr=__lowerCamelCase	)
				lowercase__		,			lowercase__   :    List[Any]				=			get_dataloaders(__lowerCamelCase						,     __lowerCamelCase	)

				# Instantiate scheduler
				lowercase__   :    Optional[int]				=			get_linear_schedule_with_warmup(
				    optimizer=__lowerCamelCase						,     num_warmup_steps=1_00						,     num_training_steps=(len(__lowerCamelCase	) * num_epochs)						,     )

				# Prepare everything
				# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
				# prepare method.
				lowercase__		,			lowercase__		,			lowercase__		,			lowercase__		,			lowercase__   :    Optional[int]				=			accelerator.prepare(
				    __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase	)

				# Now we train the model
				for epoch in range(__lowerCamelCase	):
						model.train()
						for step, batch in enumerate(__lowerCamelCase	):
								# We could avoid this line since we set the accelerator with `device_placement=True`.
								batch.to(accelerator.device	)
								lowercase__   :    Dict				=			model(**__lowerCamelCase	)
								lowercase__   :    List[Any]				=			outputs.loss
								accelerator.backward(__lowerCamelCase	)
								optimizer.step()
								lr_scheduler.step()
								optimizer.zero_grad()

						model.eval()
						for step, batch in enumerate(__lowerCamelCase	):
								# We could avoid this line since we set the accelerator with `device_placement=True`.
								batch.to(accelerator.device	)
								with torch.no_grad():
										lowercase__   :    Tuple				=			model(**__lowerCamelCase	)
								lowercase__   :    Any				=			outputs.logits.argmax(dim=-1	)
								lowercase__		,			lowercase__   :    int				=			accelerator.gather_for_metrics((predictions, batch['''labels'''])	)
								metric.add_batch(
								    predictions=__lowerCamelCase						,     references=__lowerCamelCase						,     )

						lowercase__   :    List[Any]				=			metric.compute()
						# Use accelerator.print to print only on the main process.
						accelerator.print(f"""epoch {epoch}:"""						,     __lowerCamelCase	)

    # New Code #
    # And call it at the end with no arguments
    # Note: You could also refactor this outside of your training loop function
		inner_training_loop()



def      __UpperCAmelCase      (    )							->      Dict:
		lowercase__   :    Optional[int]				=			argparse.ArgumentParser(description='''Simple example of training script.'''	)
		parser.add_argument(
		    '''--mixed_precision'''						,     type=__lowerCamelCase						,     default=__lowerCamelCase						,     choices=['''no''', '''fp16''', '''bf16''', '''fp8''']						,     help='''Whether to use mixed precision. Choose'''
		    '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
		    '''and an Nvidia Ampere GPU.'''						,     )
		parser.add_argument('''--cpu'''						,     action='''store_true'''						,     help='''If passed, will train on the CPU.'''	)
		lowercase__   :    int				=			parser.parse_args()
		lowercase__   :    Union[str, Any]				=			{'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
		training_function(__lowerCamelCase						,     __lowerCamelCase	)


if __name__ == "__main__":
							main()
