
"""simple docstring"""




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


A__   :					Any							=   1_6
A__   :					List[Any]							=   3_2




def  _lowerCAmelCase		(		_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase = 16						):






  """simple docstring"""



  _lowercase:			Optional[int]       =     AutoTokenizer.from_pretrained('''bert-base-cased'''						)
  _lowercase:			List[Any]       =     DatasetDict(
      {
          '''train''': dataset['''train'''].select(_UpperCamelCase						),
          '''validation''': dataset['''train'''].select(_UpperCamelCase						),
          '''test''': dataset['''validation'''],
      }						)

  def tokenize_function(_UpperCamelCase						):
    # max_length=None => use the model max length (it's actually the default)
    _lowercase:			Tuple       =     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():
    _lowercase:			Dict       =     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
  _lowercase:			List[str]       =     tokenized_datasets.rename_column('''label''' ,				'''labels'''						)

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

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

  # Instantiate dataloaders.
  _lowercase:			int       =     DataLoader(
      tokenized_datasets['''train'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase						)
  _lowercase:			List[Any]       =     DataLoader(
      tokenized_datasets['''validation'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase						)

  _lowercase:			List[Any]       =     DataLoader(
      tokenized_datasets['''test'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase						)

  return train_dataloader, eval_dataloader, test_dataloader




def  _lowerCAmelCase		(		_UpperCamelCase ,				_UpperCamelCase						):






  """simple docstring"""



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

  _lowercase:			List[Any]       =     evaluate.load('''glue''' ,				'''mrpc'''						)

  # If the batch size is too big we use gradient accumulation
  _lowercase:			Dict       =     1
  if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
    _lowercase:			Any       =     batch_size // MAX_GPU_BATCH_SIZE
    _lowercase:			Dict       =     MAX_GPU_BATCH_SIZE

  set_seed(_UpperCamelCase						)

  # New Code #
  # Create our folds:
  _lowercase:			int       =     kfold.split(np.zeros(datasets['''train'''].num_rows						) ,				datasets['''train''']['''label''']						)
  _lowercase:			Any       =     []
  # Iterate over them
  for i, (train_idxs, valid_idxs) in enumerate(_UpperCamelCase						):
    _lowercase ,				_lowercase ,				_lowercase:			str       =     get_fold_dataloaders(
        _UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				)
    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    _lowercase:			Union[str, Any]       =     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).
    _lowercase:			str       =     model.to(accelerator.device						)

    # Instantiate optimizer
    _lowercase:			str       =     AdamW(params=model.parameters() ,				lr=_UpperCamelCase						)

    # Instantiate scheduler
    _lowercase:			Union[str, Any]       =     get_linear_schedule_with_warmup(
        optimizer=_UpperCamelCase ,				num_warmup_steps=100 ,				num_training_steps=(len(_UpperCamelCase						) * 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.
    _lowercase ,				_lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Optional[Any]       =     accelerator.prepare(
        _UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase						)

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

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

      _lowercase:			Union[str, Any]       =     metric.compute()
      # Use accelerator.print to print only on the main process.
      accelerator.print(f'''epoch {epoch}:''' ,				_UpperCamelCase						)

    # New Code #
    # We also run predictions on the test set at the very end
    _lowercase:			Tuple       =     []
    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():
        _lowercase:			int       =     model(**_UpperCamelCase						)
      _lowercase:			Optional[int]       =     outputs.logits
      _lowercase ,				_lowercase:			Dict       =     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(_UpperCamelCase ,				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:
  _lowercase:			Optional[int]       =     torch.cat(_UpperCamelCase ,				dim=0						)
  _lowercase:			List[str]       =     torch.stack(_UpperCamelCase ,				dim=0						).sum(dim=0						).div(int(args.num_folds						)						).argmax(dim=-1						)
  _lowercase:			str       =     metric.compute(predictions=_UpperCamelCase ,				references=_UpperCamelCase						)
  accelerator.print('''Average test metrics from all folds:''' ,				_UpperCamelCase						)




def  _lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:			Dict       =     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.''' ,				)
  parser.add_argument('''--cpu''' ,				action='''store_true''' ,				help='''If passed, will train on the CPU.'''						)
  # New Code #
  parser.add_argument('''--num_folds''' ,				type=_UpperCamelCase ,				default=3 ,				help='''The number of splits to perform across the dataset'''						)
  _lowercase:			Union[str, Any]       =     parser.parse_args()
  _lowercase:			List[str]       =     {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
  training_function(_UpperCamelCase ,				_UpperCamelCase						)


if __name__ == "__main__":
  main()


"""simple docstring"""




import comet  # From: unbabel-comet
import torch

import datasets


A__   :					int							=   datasets.logging.get_logger(__name__)

A__   :					Optional[Any]							=   '\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = "{COMET}: A Neural Framework for {MT} Evaluation",\n   author = "Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon",\n   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",\n   month = nov,\n   year = "2020",\n   address = "Online",\n   publisher = "Association for Computational Linguistics",\n   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",\n   pages = "2685--2702",\n}\n'

A__   :					Union[str, Any]							=   '\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n'

A__   :					int							=   '\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric(\'comet\')\n    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use\n    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]\n    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]\n    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results["scores"]])\n    [0.19, 0.92]\n'


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,					_KWARGS_DESCRIPTION )
class 			__magic_name__       (       datasets.Metric ):
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         return datasets.MetricInfo(
             description=_DESCRIPTION ,				citation=_CITATION ,				homepage='''https://unbabel.github.io/COMET/html/index.html''' ,				inputs_description=_KWARGS_DESCRIPTION ,				features=datasets.Features(
                 {
                     '''sources''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''predictions''': datasets.Value('''string''' ,				id='''sequence'''       ),
                     '''references''': datasets.Value('''string''' ,				id='''sequence'''       ),
                 }       ) ,				codebase_urls=['''https://github.com/Unbabel/COMET'''] ,				reference_urls=[
                 '''https://github.com/Unbabel/COMET''',
                 '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
                 '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
             ] ,				)
       def 							lowercase_							(     self ,				A_       )     ->	Dict:





         """simple docstring"""




         if self.config_name == "default":
           _lowercase:			str       =     comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
         else:
           _lowercase:			Optional[Any]       =     comet.load_from_checkpoint(comet.download_model(self.config_name       )       )



       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_=None ,				A_=False       )     ->	List[str]:





         """simple docstring"""




         if gpus is None:
           _lowercase:			Union[str, Any]       =     1 if torch.cuda.is_available() else 0
         _lowercase:			Any       =     {'''src''': sources, '''mt''': predictions, '''ref''': references}
         _lowercase:			int       =     [dict(zip(A_ ,				A_       )       ) for t in zip(*data.values()       )]
         _lowercase ,				_lowercase:			Tuple       =     self.scorer.predict(A_ ,				gpus=A_ ,				progress_bar=A_       )
         return {"mean_score": mean_score, "scores": scores}
