


'''simple docstring'''



import argparse
import os

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.local_sgd import LocalSGD


########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to gradient accumulation.
#
# 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 run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


__lowercase	:						Optional[int]       =	16
__lowercase	:						List[str]       =	32






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Accelerator						,      _SCREAMING_SNAKE_CASE      :   int = 16   ):
					__a			:       Union[str, Any]					    =  AutoTokenizer.from_pretrained('bert-base-cased'   )
					__a			:       Optional[Any]					    =  load_dataset('glue'						,      'mrpc'   )

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

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

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

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

					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

	__lowercase	:						Tuple       =	mocked_dataloaders  # noqa: F811






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   int						,      _SCREAMING_SNAKE_CASE      :   Dict   ):
					# For testing only
					if os.environ.get('TESTING_MOCKED_DATALOADERS'						,      _SCREAMING_SNAKE_CASE   ) == "1":
										__a			:       Optional[int]					    =  2
					# New Code #
					__a			:       Union[str, Any]					    =  int(args.gradient_accumulation_steps   )
					__a			:       Dict					    =  int(args.local_sgd_steps   )
					# Initialize accelerator
					__a			:       Tuple					    =  Accelerator(
					    cpu=args.cpu						,      mixed_precision=args.mixed_precision						,      gradient_accumulation_steps=_SCREAMING_SNAKE_CASE   )
					if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
										raise NotImplementedError('LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)'   )
					# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
					__a			:       Dict					    =  config['lr']
					__a			:       Any					    =  int(config['num_epochs']   )
					__a			:       int					    =  int(config['seed']   )
					__a			:       List[str]					    =  int(config['batch_size']   )

					__a			:       Any					    =  evaluate.load('glue'						,      'mrpc'   )

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

					# 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).
					__a			:       Dict					    =  model.to(accelerator.device   )

					# Instantiate optimizer
					__a			:       int					    =  AdamW(params=model.parameters()						,      lr=_SCREAMING_SNAKE_CASE   )

					# Instantiate scheduler
					__a			:       Any					    =  get_linear_schedule_with_warmup(
					    optimizer=_SCREAMING_SNAKE_CASE						,      num_warmup_steps=100						,      num_training_steps=(len(_SCREAMING_SNAKE_CASE   ) * 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.
					__a    ,				__a    ,				__a    ,				__a    ,				__a			:       Any					    =  accelerator.prepare(
					    _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )

					# Now we train the model
					for epoch in range(_SCREAMING_SNAKE_CASE   ):
										model.train()
										with LocalSGD(
										    accelerator=_SCREAMING_SNAKE_CASE						,      model=_SCREAMING_SNAKE_CASE						,      local_sgd_steps=_SCREAMING_SNAKE_CASE						,      enabled=local_sgd_steps is not None   ) as local_sgd:
															for step, batch in enumerate(_SCREAMING_SNAKE_CASE   ):
																				# We could avoid this line since we set the accelerator with `device_placement=True`.
																				batch.to(accelerator.device   )
																				# New code #
																				# We use the new `accumulate` context manager to perform gradient accumulation
																				# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
																				with accelerator.accumulate(_SCREAMING_SNAKE_CASE   ):
																									__a			:       List[Any]					    =  model(**_SCREAMING_SNAKE_CASE   )
																									__a			:       int					    =  output.loss
																									accelerator.backward(_SCREAMING_SNAKE_CASE   )
																									optimizer.step()
																									lr_scheduler.step()
																									optimizer.zero_grad()
																									# LocalSGD-specific line
																									local_sgd.step()

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

										__a			:       int					    =  metric.compute()
										# Use accelerator.print to print only on the main process.
										accelerator.print(F"""epoch {epoch}:"""						,      _SCREAMING_SNAKE_CASE   )






def   lowerCamelCase							():
					__a			:       Optional[Any]					    =  argparse.ArgumentParser(description='Simple example of training script.'   )
					parser.add_argument(
					    '--mixed_precision'						,      type=_SCREAMING_SNAKE_CASE						,      default=_SCREAMING_SNAKE_CASE						,      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.'						,      )
					# New Code #
					parser.add_argument(
					    '--gradient_accumulation_steps'						,      type=_SCREAMING_SNAKE_CASE						,      default=1						,      help='The number of minibatches to be ran before gradients are accumulated.'						,      )
					parser.add_argument(
					    '--local_sgd_steps'						,      type=_SCREAMING_SNAKE_CASE						,      default=8						,      help='Number of local SGD steps or None to disable local SGD'   )
					parser.add_argument('--cpu'						,      action='store_true'						,      help='If passed, will train on the CPU.'   )
					__a			:       Optional[Any]					    =  parser.parse_args()
					__a			:       str					    =  {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
					training_function(_SCREAMING_SNAKE_CASE						,      _SCREAMING_SNAKE_CASE   )


if __name__ == "__main__":
	main()







'''simple docstring'''



import re
import string

import numpy as np

import datasets


__lowercase	:						Tuple       =	'\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowercase	:						List[str]       =	'\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowercase	:						Any       =	'\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,      _KWARGS_DESCRIPTION					)
class 							__UpperCamelCase				(		datasets.Metric					):




	def       __UpperCAmelCase							(   self							):

						'''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						,				__a						,				__a						,				__a=None						,				__a=False						,				__a=False						,				__a=False						,				):

						'''simple docstring'''





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

						if ignore_case:
											__a			:       Dict					    =  np.char.lower(__a							)
											__a			:       List[str]					    =  np.char.lower(__a							)

						if ignore_punctuation:
											__a			:       Dict					    =  string.punctuation.maketrans(''						,				''						,				string.punctuation							)
											__a			:       Tuple					    =  np.char.translate(__a						,				table=__a							)
											__a			:       Dict					    =  np.char.translate(__a						,				table=__a							)

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

						__a			:       Any					    =  predictions == references

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



