


'''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     :  Union[str, Any]											=    logging.getLogger(__name__)






def       lowercase					(_A=2 ,    _A=3 ,    _A=1_6 ,    _A = 1_0 ,    _A = 2       ):







       """simple docstring"""







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

       _lowerCAmelCase     :				List[str]       =							get_dataset(_A       )
       _lowerCAmelCase     :				Optional[int]       =							get_dataset(_A       )
       _lowerCAmelCase     :				Optional[int]       =							DataLoader(_A ,    shuffle=_A ,    batch_size=_A ,    num_workers=4       )
       _lowerCAmelCase     :				Dict       =							DataLoader(_A ,    shuffle=_A ,    batch_size=_A ,    num_workers=4       )
       return (train_dataloader, valid_dataloader)






def       lowercase					(_A ,    _A ,    _A ,    _A ,    _A ,    _A=None       ):







       """simple docstring"""







       _lowerCAmelCase     :				Dict       =							[]
       for epoch in range(_A       ):
              # Train quickly
              model.train()
              for batch in dataloader:
                     _lowerCAmelCase      ,  _lowerCAmelCase     :				Tuple       =							batch
                     _lowerCAmelCase     :				Dict       =							model(_A       )
                     _lowerCAmelCase     :				Any       =							torch.nn.functional.mse_loss(_A ,    _A       )
                     accelerator.backward(_A       )
                     optimizer.step()
                     optimizer.zero_grad()
              rands.append(random.random()       )  # Introduce some randomness
              if scheduler is not None:
                     scheduler.step()
       return rands
class 						UpperCamelCase__       (			nn.Module						):



     """simple docstring"""






     def __init__(			self ):

            '''simple docstring'''

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







     def a						(			self   ,						snake_case__ ):

            '''simple docstring'''

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



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

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

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







     def a						(			self ):

            '''simple docstring'''

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

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

                   _lowerCAmelCase     :				Any       =							train(2   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ )
                   # Save everything
                   _lowerCAmelCase     :				Optional[int]       =							os.path.join(snake_case__   ,						'checkpoint' )
                   accelerator.save_state(snake_case__ )

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







     def a						(			self ):

            '''simple docstring'''

            with tempfile.TemporaryDirectory() as tmpdir:
                   set_seed(42 )
                   _lowerCAmelCase     :				Union[str, Any]       =							DummyModel()
                   _lowerCAmelCase     :				int       =							torch.optim.Adam(params=model.parameters()   ,						lr=1E-3 )
                   _lowerCAmelCase      ,  _lowerCAmelCase     :				Any       =							dummy_dataloaders()
                   _lowerCAmelCase     :				Any       =							ProjectConfiguration(automatic_checkpoint_naming=snake_case__ )

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

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

                   _lowerCAmelCase     :				List[Any]       =							train(2   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ )
                   # Save everything
                   accelerator.save_state()

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







     def a						(			self ):

            '''simple docstring'''

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

            '''simple docstring'''

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

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







     def a						(			self ):

            '''simple docstring'''

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







     @require_cuda
     def a						(			self ):

            '''simple docstring'''

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


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



     """simple docstring"""






     __magic_name__           =     ["torch", "torchsde"]







     def __init__(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            requires_backends(self   ,						['torch', 'torchsde'] )







     @classmethod
     def a						(			cls   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            requires_backends(cls   ,						['torch', 'torchsde'] )







     @classmethod
     def a						(			cls   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            requires_backends(cls   ,						['torch', 'torchsde'] )

