






'''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							:							int  							=		logging.getLogger(__name__)






def    lowerCamelCase_     (    lowercase__=2				,     lowercase__=3				,     lowercase__=16				,     lowercase__ = 10				,     lowercase__ = 2):

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

 lowerCamelCase__  =     get_dataset(lowercase__)
 lowerCamelCase__  =     get_dataset(lowercase__)
 lowerCamelCase__  =     DataLoader(lowercase__				,     shuffle=lowercase__				,     batch_size=lowercase__				,     num_workers=4)
 lowerCamelCase__  =     DataLoader(lowercase__				,     shuffle=lowercase__				,     batch_size=lowercase__				,     num_workers=4)
 return (train_dataloader, valid_dataloader)






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__=None):
 lowerCamelCase__  =     []
 for epoch in range(lowercase__):
  # Train quickly
  model.train()
  for batch in dataloader:
   lowerCamelCase__  ,	lowerCamelCase__  =     batch
   lowerCamelCase__  =     model(lowercase__)
   lowerCamelCase__  =     torch.nn.functional.mse_loss(lowercase__				,     lowercase__)
   accelerator.backward(lowercase__)
   optimizer.step()
   optimizer.zero_grad()
  rands.append(random.random())  # Introduce some randomness
  if scheduler is not None:
   scheduler.step()
 return rands
class 				lowercase       (							nn.Module      ):


    '''simple docstring'''

    def __init__(					self     :     Dict     )							->							Tuple:

     '''simple docstring'''




     super().__init__()
     lowerCamelCase__  =     nn.Parameter(torch.randn(1     )     )
     lowerCamelCase__  =     nn.Parameter(torch.randn(1     )     )




    def    a__				(					self     :     int				,     __lowerCamelCase     :     int     )							->							int:

     '''simple docstring'''




     return x * self.a + self.b
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Tuple     )							->							Optional[Any]:

     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     torch.optim.Adam(params=model.parameters()				,     lr=1E-3     )
      lowerCamelCase__  ,	lowerCamelCase__  =     dummy_dataloaders()
      lowerCamelCase__  =     ProjectConfiguration(total_limit=1				,     project_dir=__lowerCamelCase				,     automatic_checkpoint_naming=__lowerCamelCase     )
      # Train baseline
      lowerCamelCase__  =     Accelerator(project_config=__lowerCamelCase     )
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save initial
      accelerator.save_state()

      # Save second state
      accelerator.save_state()
      self.assertEqual(len(os.listdir(accelerator.project_dir     )     )				,     1     )

    def    a__				(					self     :     str     )							->							Optional[int]:

     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     torch.optim.Adam(params=model.parameters()				,     lr=1E-3     )
      lowerCamelCase__  ,	lowerCamelCase__  =     dummy_dataloaders()
      # Train baseline
      lowerCamelCase__  =     Accelerator()
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save initial
      lowerCamelCase__  =     os.path.join(__lowerCamelCase				,     "initial"     )
      accelerator.save_state(__lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      lowerCamelCase__  =     train(3				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()

      # Train partially
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     torch.optim.Adam(params=model.parameters()				,     lr=1E-3     )
      lowerCamelCase__  ,	lowerCamelCase__  =     dummy_dataloaders()
      lowerCamelCase__  =     Accelerator()
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      accelerator.load_state(__lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )

      lowerCamelCase__  =     train(2				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save everything
      lowerCamelCase__  =     os.path.join(__lowerCamelCase				,     "checkpoint"     )
      accelerator.save_state(__lowerCamelCase     )

      # Load everything back in and make sure all states work
      accelerator.load_state(__lowerCamelCase     )
      test_rands += train(1				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )

    def    a__				(					self     :     Optional[int]     )							->							str:

     '''simple docstring'''




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

      # Train baseline
      lowerCamelCase__  =     Accelerator(project_dir=__lowerCamelCase				,     project_config=__lowerCamelCase     )
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save initial
      accelerator.save_state()
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      lowerCamelCase__  =     train(3				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()

      # Train partially
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     torch.optim.Adam(params=model.parameters()				,     lr=1E-3     )
      lowerCamelCase__  ,	lowerCamelCase__  =     dummy_dataloaders()
      lowerCamelCase__  =     ProjectConfiguration(iteration=1				,     automatic_checkpoint_naming=__lowerCamelCase     )
      lowerCamelCase__  =     Accelerator(project_dir=__lowerCamelCase				,     project_config=__lowerCamelCase     )
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      accelerator.load_state(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_0"     )     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )

      lowerCamelCase__  =     train(2				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save everything
      accelerator.save_state()

      # Load everything back in and make sure all states work
      accelerator.load_state(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_1"     )     )
      test_rands += train(1				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      ((lowerCamelCase__)  ,	(lowerCamelCase__))  =     model.a.item(), model.b.item()
      lowerCamelCase__  =     optimizer.state_dict()
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )
      self.assertEqual(__lowerCamelCase				,     __lowerCamelCase     )

    def    a__				(					self     :     Dict     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     torch.tensor([1, 2, 3]     )
     lowerCamelCase__  =     torch.tensor([2, 3, 4]     )
     lowerCamelCase__  =     DummyModel()
     lowerCamelCase__  =     torch.optim.Adam(net.parameters()     )
     lowerCamelCase__  =     Accelerator()
     with self.assertRaises(__lowerCamelCase     ) as ve:
      accelerator.register_for_checkpointing(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
     lowerCamelCase__  =     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    a__				(					self     :     Optional[Any]     )							->							List[Any]:

     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     torch.optim.Adam(params=model.parameters()				,     lr=1E-3     )
      lowerCamelCase__  =     torch.optim.lr_scheduler.StepLR(__lowerCamelCase				,     step_size=1				,     gamma=0.9_9     )
      lowerCamelCase__  ,	lowerCamelCase__  =     dummy_dataloaders()
      lowerCamelCase__  =     ProjectConfiguration(automatic_checkpoint_naming=__lowerCamelCase     )
      # Train baseline
      lowerCamelCase__  =     Accelerator(project_dir=__lowerCamelCase				,     project_config=__lowerCamelCase     )
      lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     accelerator.prepare(
          __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      # Save initial
      accelerator.save_state()
      lowerCamelCase__  =     scheduler.state_dict()
      train(3				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
      self.assertNotEqual(__lowerCamelCase				,     scheduler.state_dict()     )

      # Load everything back in and make sure all states work
      accelerator.load_state(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_0"     )     )
      self.assertEqual(__lowerCamelCase				,     scheduler.state_dict()     )

    def    a__				(					self     :     int     )							->							List[Any]:

     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42     )
      lowerCamelCase__  =     DummyModel()
      lowerCamelCase__  =     ProjectConfiguration(automatic_checkpoint_naming=__lowerCamelCase				,     total_limit=2     )
      # Train baseline
      lowerCamelCase__  =     Accelerator(project_dir=__lowerCamelCase				,     project_config=__lowerCamelCase     )
      lowerCamelCase__  =     accelerator.prepare(__lowerCamelCase     )
      # Save 3 states:
      for _ in range(11     ):
       accelerator.save_state()
      self.assertTrue(not os.path.exists(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_0"     )     )     )
      self.assertTrue(os.path.exists(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_9"     )     )     )
      self.assertTrue(os.path.exists(os.path.join(__lowerCamelCase				,     "checkpoints"				,     "checkpoint_10"     )     )     )




    @require_cuda
    def    a__				(					self     :     str     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     ["torchrun", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__     )]
     execute_subprocess_async(__lowerCamelCase				,     env=os.environ.copy()     )


if __name__ == "__main__":
 __A							:							Tuple  							=		"""/tmp/accelerate/state_checkpointing"""
 __A							:							List[str]  							=		DummyModel()
 __A							:							Optional[Any]  							=		torch.optim.Adam(params=model.parameters(), lr=1E-3)
 __A							:							Any  							=		torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
 __A							,			__A							:							List[Any]  							=		dummy_dataloaders()
 __A							:							Optional[Any]  							=		ProjectConfiguration(automatic_checkpoint_naming=True)
 # Train baseline
 __A							:							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							:							Optional[int]  							=		accelerator.prepare(
     model, optimizer, train_dataloader, valid_dataloader, scheduler
 )
 __A							,			__A							:							List[str]  							=		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							:							List[str]  							=		group["""params"""][0].device
  break
 assert param_device.type == accelerator.device.type
 __A							:							Optional[int]  							=		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							:							Optional[int]  							=		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							:							Optional[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'''





from ..utils import DummyObject, requires_backends
class 				lowercase       (							metaclass=_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["flax", "transformers"]

    def __init__(					self     :     List[str]				,     *__lowerCamelCase     :     int				,     **__lowerCamelCase     :     Any     )							->							Optional[int]:

     '''simple docstring'''




     requires_backends(self				,     ["flax", "transformers"]     )

    @classmethod
    def    a__				(					cls     :     Any				,     *__lowerCamelCase     :     Optional[int]				,     **__lowerCamelCase     :     Dict     )							->							str:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )




    @classmethod
    def    a__				(					cls     :     str				,     *__lowerCamelCase     :     str				,     **__lowerCamelCase     :     Any     )							->							str:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )
class 				lowercase       (							metaclass=_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["flax", "transformers"]

    def __init__(					self     :     str				,     *__lowerCamelCase     :     List[Any]				,     **__lowerCamelCase     :     int     )							->							List[str]:

     '''simple docstring'''




     requires_backends(self				,     ["flax", "transformers"]     )

    @classmethod
    def    a__				(					cls     :     Dict				,     *__lowerCamelCase     :     Any				,     **__lowerCamelCase     :     str     )							->							Optional[int]:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )




    @classmethod
    def    a__				(					cls     :     Any				,     *__lowerCamelCase     :     int				,     **__lowerCamelCase     :     Dict     )							->							int:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )
class 				lowercase       (							metaclass=_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["flax", "transformers"]

    def __init__(					self     :     Dict				,     *__lowerCamelCase     :     str				,     **__lowerCamelCase     :     List[Any]     )							->							str:

     '''simple docstring'''




     requires_backends(self				,     ["flax", "transformers"]     )

    @classmethod
    def    a__				(					cls     :     Optional[int]				,     *__lowerCamelCase     :     Optional[int]				,     **__lowerCamelCase     :     Optional[Any]     )							->							Dict:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )




    @classmethod
    def    a__				(					cls     :     Optional[int]				,     *__lowerCamelCase     :     Dict				,     **__lowerCamelCase     :     List[str]     )							->							Dict:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )
class 				lowercase       (							metaclass=_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["flax", "transformers"]

    def __init__(					self     :     int				,     *__lowerCamelCase     :     List[str]				,     **__lowerCamelCase     :     int     )							->							Optional[int]:

     '''simple docstring'''




     requires_backends(self				,     ["flax", "transformers"]     )

    @classmethod
    def    a__				(					cls     :     Any				,     *__lowerCamelCase     :     Tuple				,     **__lowerCamelCase     :     str     )							->							List[str]:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )




    @classmethod
    def    a__				(					cls     :     List[Any]				,     *__lowerCamelCase     :     List[str]				,     **__lowerCamelCase     :     List[Any]     )							->							int:

     '''simple docstring'''




     requires_backends(cls				,     ["flax", "transformers"]     )

