

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


lowerCAmelCase__      		=			16
lowerCAmelCase__      		=			32


def 	_A  (					A__  ,       A__ = 16   ):






 """simple docstring"""



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

 def tokenize_function(A__   ):
  # max_length=None => use the model max length (it's actually the default)
  __lowercase													=				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():
  __lowercase													=				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
 __lowercase													=				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.
  __lowercase													=				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":
   __lowercase													=				16
  elif accelerator.mixed_precision != "no":
   __lowercase													=				8
  else:
   __lowercase													=				None

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

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

 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 	_A  (					A__  ,       A__   ):






 """simple docstring"""



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

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

 set_seed(A__   )
 __lowercase						,			__lowercase													=				get_dataloaders(A__  ,       A__   )
 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
 __lowercase													=				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).
 __lowercase													=				model.to(accelerator.device   )

 # Instantiate optimizer
 __lowercase													=				AdamW(params=model.parameters()  ,       lr=A__   )

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

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

  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():
    __lowercase													=				model(**A__   )
   __lowercase													=				outputs.logits.argmax(dim=-1   )
   __lowercase						,			__lowercase													=				accelerator.gather_for_metrics((predictions, batch['''labels'''])   )
   metric.add_batch(
       predictions=A__  ,       references=A__  ,       )

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


def 	_A  (					):






 """simple docstring"""



 __lowercase													=				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.'''  ,       )
 # New Code #
 parser.add_argument(
     '''--gradient_accumulation_steps'''  ,       type=A__  ,       default=1  ,       help='''The number of minibatches to be ran before gradients are accumulated.'''  ,       )
 parser.add_argument(
     '''--local_sgd_steps'''  ,       type=A__  ,       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.'''   )
 __lowercase													=				parser.parse_args()
 __lowercase													=				{'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
 training_function(A__  ,       A__   )


if __name__ == "__main__":
 main()




'''simple docstring'''






from scipy.stats import spearmanr

import datasets


lowerCAmelCase__      		=			'''
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
'''

lowerCAmelCase__      		=			'''
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {\'spearmanr\': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric("spearmanr")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results[\'spearmanr\'])
        -0.7
        >>> print(round(results[\'spearmanr_pvalue\'], 2))
        0.19
'''

lowerCAmelCase__      		=			R'''\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@article{2020SciPy-NMeth,
  author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
            Haberland, Matt and Reddy, Tyler and Cournapeau, David and
            Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
            Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
            Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
            Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
            Kern, Robert and Larson, Eric and Carey, C J and
            Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and
            {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
            Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
            Harris, Charles R. and Archibald, Anne M. and
            Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and
            {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
  title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
            Computing in Python}},
  journal = {Nature Methods},
  year    = {2020},
  volume  = {17},
  pages   = {261--272},
  adsurl  = {https://rdcu.be/b08Wh},
  doi     = {10.1038/s41592-019-0686-2},
}
'''






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




  """simple docstring"""




  def       SCREAMING_SNAKE_CASE   (   self     :  Optional[int]    ):
   return datasets.MetricInfo(
       description=_DESCRIPTION      ,citation=_CITATION      ,inputs_description=_KWARGS_DESCRIPTION      ,features=datasets.Features(
           {
               '''predictions''': datasets.Value('''float'''    ),
               '''references''': datasets.Value('''float'''    ),
           }    )      ,reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html''']      ,)






  def       SCREAMING_SNAKE_CASE   (   self     :  Tuple      ,lowercase__     :  List[Any]      ,lowercase__     :  List[Any]      ,lowercase__     :  Union[str, Any]=False    ):
   __lowercase													=				spearmanr(lowercase__      ,lowercase__    )
   if return_pvalue:
    return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
   else:
    return {"spearmanr": results[0]}

