





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


lowerCAmelCase :					str 							=logging.getLogger(__name__)
def 							UpperCAmelCase_  (						__lowerCamelCase : str=2     ,__lowerCamelCase : str=3     ,__lowerCamelCase : List[str]=16     ,__lowerCamelCase : int = 10     ,__lowerCamelCase : int = 2			):

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

   lowercase_      :int         =			get_dataset(__lowerCamelCase			)
   lowercase_      :str         =			get_dataset(__lowerCamelCase			)
   lowercase_      :List[str]         =			DataLoader(__lowerCamelCase     ,shuffle=__lowerCamelCase     ,batch_size=__lowerCamelCase     ,num_workers=4			)
   lowercase_      :Dict         =			DataLoader(__lowerCamelCase     ,shuffle=__lowerCamelCase     ,batch_size=__lowerCamelCase     ,num_workers=4			)
   return (train_dataloader, valid_dataloader)
def 							UpperCAmelCase_  (						__lowerCamelCase : Tuple     ,__lowerCamelCase : Tuple     ,__lowerCamelCase : Union[str, Any]     ,__lowerCamelCase : Tuple     ,__lowerCamelCase : Optional[int]     ,__lowerCamelCase : str=None			):
   lowercase_      :str         =			[]
   for epoch in range(__lowerCamelCase			):
      # Train quickly
      model.train()
      for batch in dataloader:
         lowercase_      ,							lowercase_      :Dict         =			batch
         lowercase_      :Tuple         =			model(__lowerCamelCase			)
         lowercase_      :Tuple         =			torch.nn.functional.mse_loss(__lowerCamelCase     ,__lowerCamelCase			)
         accelerator.backward(__lowerCamelCase			)
         optimizer.step()
         optimizer.zero_grad()
      rands.append(random.random()			)  # Introduce some randomness
      if scheduler is not None:
         scheduler.step()
   return rands
class 				a_       (    nn.Module							):





     def __init__(			self		: List[Any]						):





        """simple docstring"""




        super().__init__()
        lowercase_      :Optional[Any]         =			nn.Parameter(torch.randn(1						)						)
        lowercase_      :List[str]         =			nn.Parameter(torch.randn(1						)						)







     def 							lowercase__				(			self		: List[str]     ,				lowercase		: Optional[int]						):





        """simple docstring"""




        return x * self.a + self.b







class 				a_       (    unittest.TestCase							):





     def 							lowercase__				(			self		: Tuple						):





        """simple docstring"""




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

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





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




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

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

           lowercase_      :Union[str, Any]         =			train(2     ,				lowercase     ,				lowercase     ,				lowercase     ,				lowercase						)
           # Save everything
           lowercase_      :List[str]         =			os.path.join(lowercase     ,				"checkpoint"						)
           accelerator.save_state(lowercase						)

           # Load everything back in and make sure all states work
           accelerator.load_state(lowercase						)
           test_rands += train(1     ,				lowercase     ,				lowercase     ,				lowercase     ,				lowercase						)
           ((lowercase_)      ,							(lowercase_))      :str         =			model.a.item(), model.b.item()
           lowercase_      :Union[str, Any]         =			optimizer.state_dict()
           self.assertEqual(lowercase     ,				lowercase						)
           self.assertEqual(lowercase     ,				lowercase						)
           self.assertEqual(lowercase     ,				lowercase						)
           self.assertEqual(lowercase     ,				lowercase						)





     def 							lowercase__				(			self		: Dict						):





        """simple docstring"""




        with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42						)
           lowercase_      :Dict         =			DummyModel()
           lowercase_      :Tuple         =			torch.optim.Adam(params=model.parameters()     ,				lr=1e-3						)
           lowercase_      ,							lowercase_      :int         =			dummy_dataloaders()
           lowercase_      :List[Any]         =			ProjectConfiguration(automatic_checkpoint_naming=lowercase						)

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

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

           lowercase_      :str         =			train(2     ,				lowercase     ,				lowercase     ,				lowercase     ,				lowercase						)
           # Save everything
           accelerator.save_state()

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





     def 							lowercase__				(			self		: int						):





        """simple docstring"""




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





        """simple docstring"""




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

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





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




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







     @require_cuda
     def 							lowercase__				(			self		: Union[str, Any]						):





        """simple docstring"""




        lowercase_      :int         =			["torchrun", F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__						)]
        execute_subprocess_async(lowercase     ,				env=os.environ.copy()						)


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





     @staticmethod
     @abstractmethod
     def 							lowercase__				(			lowercase		: ArgumentParser						):





        """simple docstring"""




        raise NotImplementedError()







     @abstractmethod
     def 							lowercase__				(			self		: str						):





        """simple docstring"""




        raise NotImplementedError()


