





import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
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


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# 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)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# 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
#
########################################################################


_SCREAMING_SNAKE_CASE 		=						16
_SCREAMING_SNAKE_CASE 		=						32


def 							SCREAMING_SNAKE_CASE__  (      __a				,	__a				,	__a				,	__a				,	__a = 16				):
	snake_case_						:     Tuple     =		AutoTokenizer.from_pretrained('bert-base-cased'				)
	snake_case_						:     Any     =		DatasetDict(
	    {
	        'train': dataset['train'].select(__a				),
	        'validation': dataset['train'].select(__a				),
	        'test': dataset['validation'],
	    }				)

	def tokenize_function(__a				):
		# max_length=None => use the model max length (it's actually the default)
		snake_case_						:     List[str]     =		tokenizer(examples['sentence1']				,	examples['sentence2']				,	truncation=__a				,	max_length=__a				)
		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():
		snake_case_						:     str     =		datasets.map(
		    __a				,	batched=__a				,	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
	snake_case_						:     Optional[int]     =		tokenized_datasets.rename_column('label'				,	'labels'				)

	def collate_fn(__a				):
		# On TPU it's best to pad everything to the same length or training will be very slow.
		snake_case_						:     List[Any]     =		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":
			snake_case_						:     Dict     =		16
		elif accelerator.mixed_precision != "no":
			snake_case_						:     int     =		8
		else:
			snake_case_						:     Optional[int]     =		None

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

	# Instantiate dataloaders.
	snake_case_						:     Union[str, Any]     =		DataLoader(
	    tokenized_datasets['train']				,	shuffle=__a				,	collate_fn=__a				,	batch_size=__a				)
	snake_case_						:     Union[str, Any]     =		DataLoader(
	    tokenized_datasets['validation']				,	shuffle=__a				,	collate_fn=__a				,	batch_size=__a				)

	snake_case_						:     Any     =		DataLoader(
	    tokenized_datasets['test']				,	shuffle=__a				,	collate_fn=__a				,	batch_size=__a				)

	return train_dataloader, eval_dataloader, test_dataloader


def 							SCREAMING_SNAKE_CASE__  (      __a				,	__a				):
	# New Code #
	snake_case_						:     Tuple     =		[]
	# Download the dataset
	snake_case_						:     List[Any]     =		load_dataset('glue'				,	'mrpc'				)
	# Create our splits
	snake_case_						:     Tuple     =		StratifiedKFold(n_splits=int(args.num_folds				)				)
	# Initialize accelerator
	snake_case_						:     List[str]     =		Accelerator(cpu=args.cpu				,	mixed_precision=args.mixed_precision				)
	# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
	snake_case_						:     Tuple     =		config['lr']
	snake_case_						:     Any     =		int(config['num_epochs']				)
	snake_case_						:     Tuple     =		int(config['seed']				)
	snake_case_						:     Dict     =		int(config['batch_size']				)

	snake_case_						:     Optional[Any]     =		evaluate.load('glue'				,	'mrpc'				)

	# If the batch size is too big we use gradient accumulation
	snake_case_						:     Dict     =		1
	if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
		snake_case_						:     Union[str, Any]     =		batch_size // MAX_GPU_BATCH_SIZE
		snake_case_						:     List[Any]     =		MAX_GPU_BATCH_SIZE

	set_seed(__a				)

	# New Code #
	# Create our folds:
	snake_case_						:     List[str]     =		kfold.split(np.zeros(datasets['train'].num_rows				)				,	datasets['train']['label']				)
	snake_case_						:     Tuple     =		[]
	# Iterate over them
	for i, (train_idxs, valid_idxs) in enumerate(__a				):
		snake_case_  ,snake_case_  ,snake_case_						:     Any     =		get_fold_dataloaders(
		    __a				,	__a				,	__a				,	__a				,	)
		# Instantiate the model (we build the model here so that the seed also control new weights initialization)
		snake_case_						:     Any     =		AutoModelForSequenceClassification.from_pretrained('bert-base-cased'				,	return_dict=__a				)

		# 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).
		snake_case_						:     List[str]     =		model.to(accelerator.device				)

		# Instantiate optimizer
		snake_case_						:     List[Any]     =		AdamW(params=model.parameters()				,	lr=__a				)

		# Instantiate scheduler
		snake_case_						:     Any     =		get_linear_schedule_with_warmup(
		    optimizer=__a				,	num_warmup_steps=1_00				,	num_training_steps=(len(__a				) * num_epochs) // gradient_accumulation_steps				,	)

		# 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.
		snake_case_  ,snake_case_  ,snake_case_  ,snake_case_  ,snake_case_						:     List[Any]     =		accelerator.prepare(
		    __a				,	__a				,	__a				,	__a				,	__a				)

		# Now we train the model
		for epoch in range(__a				):
			model.train()
			for step, batch in enumerate(__a				):
				# We could avoid this line since we set the accelerator with `device_placement=True`.
				batch.to(accelerator.device				)
				snake_case_						:     str     =		model(**__a				)
				snake_case_						:     int     =		outputs.loss
				snake_case_						:     List[Any]     =		loss / gradient_accumulation_steps
				accelerator.backward(__a				)
				if step % gradient_accumulation_steps == 0:
					optimizer.step()
					lr_scheduler.step()
					optimizer.zero_grad()

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

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

		# New Code #
		# We also run predictions on the test set at the very end
		snake_case_						:     Any     =		[]
		for step, batch in enumerate(__a				):
			# We could avoid this line since we set the accelerator with `device_placement=True`.
			batch.to(accelerator.device				)
			with torch.no_grad():
				snake_case_						:     Union[str, Any]     =		model(**__a				)
			snake_case_						:     Optional[int]     =		outputs.logits
			snake_case_  ,snake_case_						:     int     =		accelerator.gather_for_metrics((predictions, batch['labels'])				)
			fold_predictions.append(predictions.cpu()				)
			if i == 0:
				# We need all of the test predictions
				test_references.append(references.cpu()				)
        # Use accelerator.print to print only on the main process.
		test_predictions.append(torch.cat(__a				,	dim=0				)				)
		# We now need to release all our memory and get rid of the current model, optimizer, etc
		accelerator.free_memory()
	# New Code #
	# Finally we check the accuracy of our folded results:
	snake_case_						:     List[Any]     =		torch.cat(__a				,	dim=0				)
	snake_case_						:     Tuple     =		torch.stack(__a				,	dim=0				).sum(dim=0				).div(int(args.num_folds				)				).argmax(dim=-1				)
	snake_case_						:     List[Any]     =		metric.compute(predictions=__a				,	references=__a				)
	accelerator.print('Average test metrics from all folds:'				,	__a				)


def 							SCREAMING_SNAKE_CASE__  (      ):
	snake_case_						:     Optional[int]     =		argparse.ArgumentParser(description='Simple example of training script.'				)
	parser.add_argument(
	    '--mixed_precision'				,	type=__a				,	default=__a				,	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.'				)
	# New Code #
	parser.add_argument('--num_folds'				,	type=__a				,	default=3				,	help='The number of splits to perform across the dataset'				)
	snake_case_						:     Tuple     =		parser.parse_args()
	snake_case_						:     Any     =		{'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
	training_function(__a				,	__a				)


if __name__ == "__main__":
						main()








import re
import string

import numpy as np

import datasets


_SCREAMING_SNAKE_CASE 		=						"""
Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.
"""

_SCREAMING_SNAKE_CASE 		=						"""
Args:
    predictions: List of predicted texts.
    references: List of reference texts.
    regexes_to_ignore: List, defaults to None. Regex expressions of characters to
        ignore when calculating the exact matches. Note: these regexes are removed
        from the input data before the changes based on the options below (e.g. ignore_case,
        ignore_punctuation, ignore_numbers) are applied.
    ignore_case: Boolean, defaults to False. If true, turns everything
        to lowercase so that capitalization differences are ignored.
    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before
        comparing predictions and references.
Returns:
    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.
Examples:
    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    25.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    50.0


    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)
    >>> print(round(results[\"exact_match\"], 1))
    75.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]
    >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]
    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)
    >>> print(round(results[\"exact_match\"], 1))
    100.0

    >>> exact_match = datasets.load_metric(\"exact_match\")
    >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]
    >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]
    >>> results = exact_match.compute(references=refs, predictions=preds)
    >>> print(round(results[\"exact_match\"], 1))
    33.3

"""

_SCREAMING_SNAKE_CASE 		=						"""
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,			_KWARGS_DESCRIPTION   )
class SCREAMING_SNAKE_CASE_  (   datasets.Metric   ):






						def UpperCAmelCase_			( self : Union[str, Any]		)							->      Optional[Any]:







							"""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'		),
							        }		)						,				reference_urls=[]						,				)






						def UpperCAmelCase_			( self : List[Any]						,				_A : Optional[Any]						,				_A : Optional[int]						,				_A : Optional[int]=None						,				_A : Dict=False						,				_A : Dict=False						,				_A : Optional[Any]=False						,				)							->      List[str]:







							"""simple docstring"""


							if regexes_to_ignore is not None:
								for s in regexes_to_ignore:
									snake_case_						:     List[str]     =		np.array([re.sub(_A						,				''						,				_A		) for x in predictions]		)
									snake_case_						:     int     =		np.array([re.sub(_A						,				''						,				_A		) for x in references]		)
							else:
								snake_case_						:     Optional[Any]     =		np.asarray(_A		)
								snake_case_						:     Optional[Any]     =		np.asarray(_A		)

							if ignore_case:
								snake_case_						:     int     =		np.char.lower(_A		)
								snake_case_						:     List[str]     =		np.char.lower(_A		)

							if ignore_punctuation:
								snake_case_						:     str     =		string.punctuation.maketrans(''						,				''						,				string.punctuation		)
								snake_case_						:     str     =		np.char.translate(_A						,				table=_A		)
								snake_case_						:     Any     =		np.char.translate(_A						,				table=_A		)

							if ignore_numbers:
								snake_case_						:     int     =		string.digits.maketrans(''						,				''						,				string.digits		)
								snake_case_						:     Tuple     =		np.char.translate(_A						,				table=_A		)
								snake_case_						:     Optional[Any]     =		np.char.translate(_A						,				table=_A		)

							snake_case_						:     Optional[Any]     =		predictions == references

							return {"exact_match": np.mean(_A		) * 100}

