


'''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
#
########################################################################


a_    :			str      				=			1_6
a_    :			Dict      				=			3_2






def 		_A (lowerCAmelCase__     :List[str] ,  lowerCAmelCase__     :Dict = 16						)      ->     Optional[Any]:




     '''simple docstring'''



     _a						=							AutoTokenizer.from_pretrained('bert-base-cased'						)
     _a						=							load_dataset('glue' ,  'mrpc'						)

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

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

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

     # Instantiate dataloaders.
     _a						=							DataLoader(
         tokenized_datasets['train'] ,  shuffle=__UpperCAmelCase ,  collate_fn=__UpperCAmelCase ,  batch_size=__UpperCAmelCase						)
     _a						=							DataLoader(
         tokenized_datasets['validation'] ,  shuffle=__UpperCAmelCase ,  collate_fn=__UpperCAmelCase ,  batch_size=__UpperCAmelCase						)

     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

 a_    :			Dict      				=			mocked_dataloaders  # noqa: F811






def 		_A (lowerCAmelCase__     :List[Any] ,  lowerCAmelCase__     :int						)      ->     Any:




     '''simple docstring'''



     if os.environ.get('TESTING_MOCKED_DATALOADERS' ,  __UpperCAmelCase						) == "1":
          _a						=							2
     # New Code #
     _a						=							int(args.gradient_accumulation_steps						)
     _a						=							int(args.local_sgd_steps						)
     # Initialize accelerator
     _a						=							Accelerator(
         cpu=args.cpu ,  mixed_precision=args.mixed_precision ,  gradient_accumulation_steps=__UpperCAmelCase						)
     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						=							config['''lr''']
     _a						=							int(config['num_epochs']						)
     _a						=							int(config['seed']						)
     _a						=							int(config['batch_size']						)

     _a						=							evaluate.load('glue' ,  'mrpc'						)

     set_seed(__UpperCAmelCase						)
     _a						=							get_dataloaders(__UpperCAmelCase ,  __UpperCAmelCase						)
     # Instantiate the model (we build the model here so that the seed also control new weights initialization)
     _a						=							AutoModelForSequenceClassification.from_pretrained('bert-base-cased' ,  return_dict=__UpperCAmelCase						)

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

     # Instantiate optimizer
     _a						=							AdamW(params=model.parameters() ,  lr=__UpperCAmelCase						)

     # Instantiate scheduler
     _a						=							get_linear_schedule_with_warmup(
         optimizer=__UpperCAmelCase ,  num_warmup_steps=1_00 ,  num_training_steps=(len(__UpperCAmelCase						) * 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						=							accelerator.prepare(
         __UpperCAmelCase ,  __UpperCAmelCase ,  __UpperCAmelCase ,  __UpperCAmelCase ,  __UpperCAmelCase						)

     # Now we train the model
     for epoch in range(__UpperCAmelCase						):
          model.train()
          with LocalSGD(
              accelerator=__UpperCAmelCase ,  model=__UpperCAmelCase ,  local_sgd_steps=__UpperCAmelCase ,  enabled=local_sgd_steps is not None						) as local_sgd:
               for step, batch in enumerate(__UpperCAmelCase						):
                    # 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(__UpperCAmelCase						):
                         _a						=							model(**__UpperCAmelCase						)
                         _a						=							output.loss
                         accelerator.backward(__UpperCAmelCase						)
                         optimizer.step()
                         lr_scheduler.step()
                         optimizer.zero_grad()
                         # LocalSGD-specific line
                         local_sgd.step()

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

          _a						=							metric.compute()
          # Use accelerator.print to print only on the main process.
          accelerator.print(f'epoch {epoch}:' ,  __UpperCAmelCase						)






def 		_A ()      ->     Optional[Any]:




     '''simple docstring'''



     _a						=							argparse.ArgumentParser(description='Simple example of training script.'						)
     parser.add_argument(
         '--mixed_precision' ,  type=__UpperCAmelCase ,  default=__UpperCAmelCase ,  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=__UpperCAmelCase ,  default=1 ,  help='The number of minibatches to be ran before gradients are accumulated.' ,  )
     parser.add_argument(
         '--local_sgd_steps' ,  type=__UpperCAmelCase ,  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						=							parser.parse_args()
     _a						=							{'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
     training_function(__UpperCAmelCase ,  __UpperCAmelCase						)


if __name__ == "__main__":
 main()


"""simple docstring"""






from jiwer import compute_measures

import datasets


__A			   = "\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n"

__A			   = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

__A			   = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"


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



    """simple docstring"""

    def _snake_case			(   self							):
       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/jitsi/jiwer/''']    ,			reference_urls=[
               '''https://en.wikipedia.org/wiki/Word_error_rate''',
           ]    ,			)






    def _snake_case			(   self    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=None    ,			_UpperCAmelCase=False							):
       if concatenate_texts:
          return compute_measures(_UpperCAmelCase    ,			_UpperCAmelCase							)["wer"]
       else:
          lowercase__:   Dict					=      0
          lowercase__:   Union[str, Any]					=      0
          for prediction, reference in zip(_UpperCAmelCase    ,			_UpperCAmelCase							):
             lowercase__:   Tuple					=      compute_measures(_UpperCAmelCase    ,			_UpperCAmelCase							)
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]
          return incorrect / total
