
"""simple docstring"""




import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


A__   :					str							=   logging.getLogger(__name__)




def  _lowerCAmelCase		(		_UpperCamelCase=2 ,				_UpperCamelCase=3 ,				_UpperCamelCase=16 ,				_UpperCamelCase = 10 ,				_UpperCamelCase = 2						):






  """simple docstring"""



  def get_dataset(_UpperCamelCase						):
    _lowercase:			int       =     torch.randn(batch_size * n_batches ,				1						)
    return TensorDataset(_UpperCamelCase ,				a * x + b + 0.1 * torch.randn(batch_size * n_batches ,				1						)						)

  _lowercase:			List[Any]       =     get_dataset(_UpperCamelCase						)
  _lowercase:			Optional[Any]       =     get_dataset(_UpperCamelCase						)
  _lowercase:			List[str]       =     DataLoader(_UpperCamelCase ,				shuffle=_UpperCamelCase ,				batch_size=_UpperCamelCase ,				num_workers=4						)
  _lowercase:			Dict       =     DataLoader(_UpperCamelCase ,				shuffle=_UpperCamelCase ,				batch_size=_UpperCamelCase ,				num_workers=4						)
  return (train_dataloader, valid_dataloader)




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






  """simple docstring"""



  _lowercase:			str       =     []
  for epoch in range(_UpperCamelCase						):
    # Train quickly
    model.train()
    for batch in dataloader:
      _lowercase ,				_lowercase:			Optional[Any]       =     batch
      _lowercase:			Dict       =     model(_UpperCamelCase						)
      _lowercase:			List[Any]       =     torch.nn.functional.mse_loss(_UpperCamelCase ,				_UpperCamelCase						)
      accelerator.backward(_UpperCamelCase						)
      optimizer.step()
      optimizer.zero_grad()
    rands.append(random.random()						)  # Introduce some randomness
    if scheduler is not None:
      scheduler.step()
  return rands


class 			__magic_name__       (       nn.Module ):
       def __init__(     self       )     ->	int:





         """simple docstring"""




         super().__init__()
         _lowercase:			Union[str, Any]       =     nn.Parameter(torch.randn(1       )       )
         _lowercase:			Optional[int]       =     nn.Parameter(torch.randn(1       )       )



       def 							lowercase_							(     self ,				A_       )     ->	Optional[Any]:





         """simple docstring"""




         return x * self.a + self.b


class 			__magic_name__       (       unittest.TestCase ):
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42       )
           _lowercase:			Dict       =     DummyModel()
           _lowercase:			Any       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase ,				_lowercase:			int       =     dummy_dataloaders()
           _lowercase:			Any       =     ProjectConfiguration(total_limit=1 ,				project_dir=A_ ,				automatic_checkpoint_naming=A_       )
           # Train baseline
           _lowercase:			List[str]       =     Accelerator(project_config=A_       )
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Any       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_       )
           # Save initial
           accelerator.save_state()

           # Save second state
           accelerator.save_state()
           self.assertEqual(len(os.listdir(accelerator.project_dir       )       ) ,				1       )
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42       )
           _lowercase:			List[str]       =     DummyModel()
           _lowercase:			List[Any]       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase ,				_lowercase:			Tuple       =     dummy_dataloaders()
           # Train baseline
           _lowercase:			str       =     Accelerator()
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Any       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_       )
           # Save initial
           _lowercase:			List[str]       =     os.path.join(A_ ,				'''initial'''       )
           accelerator.save_state(A_       )
           ((_lowercase) ,				(_lowercase)):			Tuple       =     model.a.item(), model.b.item()
           _lowercase:			Optional[Any]       =     optimizer.state_dict()
           _lowercase:			Tuple       =     train(3 ,				A_ ,				A_ ,				A_ ,				A_       )
           ((_lowercase) ,				(_lowercase)):			List[str]       =     model.a.item(), model.b.item()
           _lowercase:			Dict       =     optimizer.state_dict()

           # Train partially
           set_seed(42       )
           _lowercase:			int       =     DummyModel()
           _lowercase:			str       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase ,				_lowercase:			List[Any]       =     dummy_dataloaders()
           _lowercase:			str       =     Accelerator()
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Dict       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_       )
           accelerator.load_state(A_       )
           ((_lowercase) ,				(_lowercase)):			List[str]       =     model.a.item(), model.b.item()
           _lowercase:			Union[str, Any]       =     optimizer.state_dict()
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )

           _lowercase:			List[str]       =     train(2 ,				A_ ,				A_ ,				A_ ,				A_       )
           # Save everything
           _lowercase:			Optional[int]       =     os.path.join(A_ ,				'''checkpoint'''       )
           accelerator.save_state(A_       )

           # Load everything back in and make sure all states work
           accelerator.load_state(A_       )
           test_rands += train(1 ,				A_ ,				A_ ,				A_ ,				A_       )
           ((_lowercase) ,				(_lowercase)):			Any       =     model.a.item(), model.b.item()
           _lowercase:			Optional[int]       =     optimizer.state_dict()
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42       )
           _lowercase:			int       =     DummyModel()
           _lowercase:			int       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase ,				_lowercase:			Tuple       =     dummy_dataloaders()
           _lowercase:			Dict       =     ProjectConfiguration(automatic_checkpoint_naming=A_       )

           # Train baseline
           _lowercase:			Tuple       =     Accelerator(project_dir=A_ ,				project_config=A_       )
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Union[str, Any]       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_       )
           # Save initial
           accelerator.save_state()
           ((_lowercase) ,				(_lowercase)):			List[str]       =     model.a.item(), model.b.item()
           _lowercase:			Dict       =     optimizer.state_dict()
           _lowercase:			Optional[Any]       =     train(3 ,				A_ ,				A_ ,				A_ ,				A_       )
           ((_lowercase) ,				(_lowercase)):			int       =     model.a.item(), model.b.item()
           _lowercase:			Union[str, Any]       =     optimizer.state_dict()

           # Train partially
           set_seed(42       )
           _lowercase:			List[Any]       =     DummyModel()
           _lowercase:			Optional[int]       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase ,				_lowercase:			List[Any]       =     dummy_dataloaders()
           _lowercase:			Dict       =     ProjectConfiguration(iteration=1 ,				automatic_checkpoint_naming=A_       )
           _lowercase:			Optional[Any]       =     Accelerator(project_dir=A_ ,				project_config=A_       )
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Dict       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_       )
           accelerator.load_state(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_0'''       )       )
           ((_lowercase) ,				(_lowercase)):			Union[str, Any]       =     model.a.item(), model.b.item()
           _lowercase:			int       =     optimizer.state_dict()
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )

           _lowercase:			Optional[Any]       =     train(2 ,				A_ ,				A_ ,				A_ ,				A_       )
           # Save everything
           accelerator.save_state()

           # Load everything back in and make sure all states work
           accelerator.load_state(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_1'''       )       )
           test_rands += train(1 ,				A_ ,				A_ ,				A_ ,				A_       )
           ((_lowercase) ,				(_lowercase)):			List[Any]       =     model.a.item(), model.b.item()
           _lowercase:			Optional[Any]       =     optimizer.state_dict()
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
           self.assertEqual(A_ ,				A_       )
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			str       =     torch.tensor([1, 2, 3]       )
         _lowercase:			Dict       =     torch.tensor([2, 3, 4]       )
         _lowercase:			int       =     DummyModel()
         _lowercase:			int       =     torch.optim.Adam(net.parameters()       )
         _lowercase:			Optional[Any]       =     Accelerator()
         with self.assertRaises(A_       ) as ve:
           accelerator.register_for_checkpointing(A_ ,				A_ ,				A_ ,				A_       )
         _lowercase:			Optional[Any]       =     str(ve.exception       )
         self.assertTrue('''Item at index 0''' in message       )
         self.assertTrue('''Item at index 1''' in message       )
         self.assertFalse('''Item at index 2''' in message       )
         self.assertFalse('''Item at index 3''' in message       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42       )
           _lowercase:			Dict       =     DummyModel()
           _lowercase:			List[Any]       =     torch.optim.Adam(params=model.parameters() ,				lr=1E-3       )
           _lowercase:			int       =     torch.optim.lr_scheduler.StepLR(A_ ,				step_size=1 ,				gamma=0.99       )
           _lowercase ,				_lowercase:			Optional[int]       =     dummy_dataloaders()
           _lowercase:			Any       =     ProjectConfiguration(automatic_checkpoint_naming=A_       )
           # Train baseline
           _lowercase:			Tuple       =     Accelerator(project_dir=A_ ,				project_config=A_       )
           _lowercase ,				_lowercase ,				_lowercase ,				_lowercase ,				_lowercase:			Optional[Any]       =     accelerator.prepare(
               A_ ,				A_ ,				A_ ,				A_ ,				A_       )
           # Save initial
           accelerator.save_state()
           _lowercase:			List[Any]       =     scheduler.state_dict()
           train(3 ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )
           self.assertNotEqual(A_ ,				scheduler.state_dict()       )

           # Load everything back in and make sure all states work
           accelerator.load_state(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_0'''       )       )
           self.assertEqual(A_ ,				scheduler.state_dict()       )
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42       )
           _lowercase:			List[Any]       =     DummyModel()
           _lowercase:			Union[str, Any]       =     ProjectConfiguration(automatic_checkpoint_naming=A_ ,				total_limit=2       )
           # Train baseline
           _lowercase:			Union[str, Any]       =     Accelerator(project_dir=A_ ,				project_config=A_       )
           _lowercase:			str       =     accelerator.prepare(A_       )
           # Save 3 states:
           for _ in range(11       ):
             accelerator.save_state()
           self.assertTrue(not os.path.exists(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_0'''       )       )       )
           self.assertTrue(os.path.exists(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_9'''       )       )       )
           self.assertTrue(os.path.exists(os.path.join(A_ ,				'''checkpoints''' ,				'''checkpoint_10'''       )       )       )



       @require_cuda
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         _lowercase:			Any       =     ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__       )]
         execute_subprocess_async(A_ ,				env=os.environ.copy()       )


if __name__ == "__main__":
  A__   :					Tuple							=   '/tmp/accelerate/state_checkpointing'
  A__   :					Optional[int]							=   DummyModel()
  A__   :					int							=   torch.optim.Adam(params=model.parameters(), lr=1e-3)
  A__   :					Optional[int]							=   torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
  A__							, A__   :					Optional[int]							=   dummy_dataloaders()
  A__   :					List[Any]							=   ProjectConfiguration(automatic_checkpoint_naming=True)
  # Train baseline
  A__   :					Optional[int]							=   Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no')
  if accelerator.process_index == 0:
    if os.path.exists(savedir):
      shutil.rmtree(savedir)
    os.makedirs(savedir)
  A__							, A__							, A__							, A__							, A__   :					Tuple							=   accelerator.prepare(
      model, optimizer, train_dataloader, valid_dataloader, scheduler
  )
  A__							, A__   :					Tuple							=   accelerator.prepare(model, optimizer)
  train(3, model, train_dataloader, optimizer, accelerator, scheduler)
  # Check that the intial optimizer is loaded on the GPU
  for group in optimizer.param_groups:
    A__   :					Optional[int]							=   group['params'][0].device
    break
  assert param_device.type == accelerator.device.type
  A__   :					Dict							=   model.cpu()
  accelerator.wait_for_everyone()
  accelerator.save_state()
  accelerator.wait_for_everyone()

  # Check CPU state
  accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu')
  for group in optimizer.param_groups:
    A__   :					List[Any]							=   group['params'][0].device
    break
  assert (
      param_device.type == torch.device('cpu').type
  ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

  # Check device state
  model.to(accelerator.device)
  accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device')
  for group in optimizer.param_groups:
    A__   :					Any							=   group['params'][0].device
    break
  assert (
      param_device.type == accelerator.device.type
  ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

  # Check error
  with pytest.raises(TypeError, match='Unsupported optimizer map location passed'):
    accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid')
  accelerator.wait_for_everyone()
  if accelerator.process_index == 0:
    shutil.rmtree(savedir)
  accelerator.wait_for_everyone()


"""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}
