



'''simple docstring'''





from sklearn.metrics import matthews_corrcoef

import datasets


__a  			=						"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

__a  			=						"\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

__a  			=						"\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,						_KWARGS_DESCRIPTION      )
class        UpperCAmelCase_			(			datasets.Metric      ):
    """simple docstring"""







    def lowerCamelCase			(       self   :	Any		):
          return datasets.MetricInfo(
              description=_DESCRIPTION					,	citation=_CITATION					,	inputs_description=_KWARGS_DESCRIPTION					,	features=datasets.Features(
                  {
                      """predictions""": datasets.Value("""int32"""		),
                      """references""": datasets.Value("""int32"""		),
                  }		)					,	reference_urls=[
                  """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"""
              ]					,	)




    def lowerCamelCase			(       self   :	List[Any]					,	snake_case_   :	List[Any]					,	snake_case_   :	List[str]					,	snake_case_   :	Optional[Any]=None		):
          return {
              "matthews_correlation": float(matthews_corrcoef(snake_case_					,	snake_case_					,	sample_weight=snake_case_		)		),
          }





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


########################################################################
# This is a fully working simple example to use Accelerate
# and perform 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  			=						16
__a  			=						32





def 		__snake_case(							_lowerCAmelCase	,  _lowerCAmelCase = 16						)						->					Optional[Any]:
      snake_case__    :       Optional[int]       		= AutoTokenizer.from_pretrained("""bert-base-cased"""						)
      snake_case__    :       Optional[int]       		= load_dataset("""glue"""	,  """mrpc"""						)

      def tokenize_function(_lowerCAmelCase						):
            # max_length=None => use the model max length (it's actually the default)
            snake_case__    :       Union[str, Any]       		= 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():
            snake_case__    :       List[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
      snake_case__    :       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.
            snake_case__    :       List[str]       		= 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":
                  snake_case__    :       Optional[Any]       		= 16
            elif accelerator.mixed_precision != "no":
                  snake_case__    :       Tuple       		= 8
            else:
                  snake_case__    :       int       		= None

            return tokenizer.pad(
                _lowerCAmelCase	,  padding="""longest"""	,  max_length=_lowerCAmelCase	,  pad_to_multiple_of=_lowerCAmelCase	,  return_tensors="""pt"""	,  )

      # Instantiate dataloaders.
      snake_case__    :       List[Any]       		= DataLoader(
          tokenized_datasets["""train"""]	,  shuffle=_lowerCAmelCase	,  collate_fn=_lowerCAmelCase	,  batch_size=_lowerCAmelCase						)
      snake_case__    :       Dict       		= 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

       __a  			=						mocked_dataloaders  # noqa: F811





def 		__snake_case(							_lowerCAmelCase	,  _lowerCAmelCase						)						->					int:
      # For testing only
      if os.environ.get("""TESTING_MOCKED_DATALOADERS"""	,  _lowerCAmelCase						) == "1":
            snake_case__    :       int       		= 2
      # New Code #
      snake_case__    :       Any       		= int(args.gradient_accumulation_steps						)
      # Initialize accelerator
      snake_case__    :       Any       		= Accelerator(
          cpu=args.cpu	,  mixed_precision=args.mixed_precision	,  gradient_accumulation_steps=_lowerCAmelCase						)
      if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1:
            raise NotImplementedError(
                """Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"""						)
      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      snake_case__    :       List[Any]       		= config["""lr"""]
      snake_case__    :       Optional[Any]       		= int(config["""num_epochs"""]						)
      snake_case__    :       Union[str, Any]       		= int(config["""seed"""]						)
      snake_case__    :       List[str]       		= int(config["""batch_size"""]						)

      snake_case__    :       Union[str, Any]       		= evaluate.load("""glue"""	,  """mrpc"""						)

      set_seed(_lowerCAmelCase						)
      snake_case__		,							snake_case__    :       Tuple       		= get_dataloaders(_lowerCAmelCase	,  _lowerCAmelCase						)
      # Instantiate the model (we build the model here so that the seed also control new weights initialization)
      snake_case__    :       Optional[int]       		= 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).
      snake_case__    :       Tuple       		= model.to(accelerator.device						)

      # Instantiate optimizer
      snake_case__    :       Any       		= AdamW(params=model.parameters()	,  lr=_lowerCAmelCase						)

      # Instantiate scheduler
      snake_case__    :       List[Any]       		= get_linear_schedule_with_warmup(
          optimizer=_lowerCAmelCase	,  num_warmup_steps=100	,  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.
      snake_case__		,							snake_case__		,							snake_case__		,							snake_case__		,							snake_case__    :       List[Any]       		= 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						)
                  # 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(_lowerCAmelCase						):
                        snake_case__    :       Any       		= model(**_lowerCAmelCase						)
                        snake_case__    :       str       		= output.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():
                        snake_case__    :       str       		= model(**_lowerCAmelCase						)
                  snake_case__    :       Optional[int]       		= outputs.logits.argmax(dim=-1						)
                  snake_case__		,							snake_case__    :       List[Any]       		= accelerator.gather_for_metrics((predictions, batch["""labels"""])						)
                  metric.add_batch(
                      predictions=_lowerCAmelCase	,  references=_lowerCAmelCase	,  )

            snake_case__    :       str       		= metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(f"epoch {epoch}:"	,  _lowerCAmelCase						)





def 		__snake_case(							)						->					List[str]:
      snake_case__    :       List[str]       		= 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."""	,  )
      # New Code #
      parser.add_argument(
          """--gradient_accumulation_steps"""	,  type=_lowerCAmelCase	,  default=1	,  help="""The number of minibatches to be ran before gradients are accumulated."""	,  )
      parser.add_argument("""--cpu"""	,  action="""store_true"""	,  help="""If passed, will train on the CPU."""						)
      snake_case__    :       Tuple       		= parser.parse_args()
      snake_case__    :       Dict       		= {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
      training_function(_lowerCAmelCase	,  _lowerCAmelCase						)


if __name__ == "__main__":
       main()
