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


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__=2			,		UpperCamelCase__=3			,		UpperCamelCase__=1_6			,		UpperCamelCase__ = 1_0			,		UpperCamelCase__ = 2		):

      def get_dataset(UpperCamelCase__		):
            UpperCamelCase__     : Optional[int]											=					torch.randn(batch_size * n_batches			,		1		)
            return TensorDataset(UpperCamelCase__			,		a * x + b + 0.1 * torch.randn(batch_size * n_batches			,		1		)		)

      UpperCamelCase__     : Union[str, Any]											=					get_dataset(UpperCamelCase__		)
      UpperCamelCase__     : List[str]											=					get_dataset(UpperCamelCase__		)
      UpperCamelCase__     : Union[str, Any]											=					DataLoader(UpperCamelCase__			,		shuffle=UpperCamelCase__			,		batch_size=UpperCamelCase__			,		num_workers=4		)
      UpperCamelCase__     : str											=					DataLoader(UpperCamelCase__			,		shuffle=UpperCamelCase__			,		batch_size=UpperCamelCase__			,		num_workers=4		)
      return (train_dataloader, valid_dataloader)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__			,		UpperCamelCase__			,		UpperCamelCase__			,		UpperCamelCase__			,		UpperCamelCase__=None		):
      UpperCamelCase__     : int											=					[]
      for epoch in range(UpperCamelCase__		):
            # Train quickly
            model.train()
            for batch in dataloader:
                  UpperCamelCase__					,UpperCamelCase__     : Optional[Any]											=					batch
                  UpperCamelCase__     : int											=					model(UpperCamelCase__		)
                  UpperCamelCase__     : Optional[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 					_lowerCamelCase			(   nn.Module			):





     """simple docstring"""







     def __init__(				self	)	-> Dict:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> Any:




           """simple docstring"""







           return x * self.a + self.b




class 					_lowerCamelCase			(   unittest.TestCase			):





     """simple docstring"""







     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Optional[int]:




           """simple docstring"""







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

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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







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

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

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

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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







           with tempfile.TemporaryDirectory() as tmpdir:
                 set_seed(4_2	)
                 UpperCamelCase__     : Union[str, Any]											=					DummyModel()
                 UpperCamelCase__     : str											=					torch.optim.Adam(params=model.parameters()    ,    lr=1e-3	)
                 UpperCamelCase__					,UpperCamelCase__     : int											=					dummy_dataloaders()
                 UpperCamelCase__     : str											=					ProjectConfiguration(automatic_checkpoint_naming=__SCREAMING_SNAKE_CASE	)

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

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

                 UpperCamelCase__     : str											=					train(2    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	)
                 # Save everything
                 accelerator.save_state()

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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Union[str, Any]:




           """simple docstring"""







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




           """simple docstring"""







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

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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







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






     @require_cuda
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Dict:




           """simple docstring"""







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


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




def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__ = " "		):
      UpperCamelCase__     : Optional[int]											=					[]

      UpperCamelCase__     : int											=					0
      for index, char in enumerate(UpperCamelCase__		):
            if char == separator:
                  split_words.append(string[last_index:index]		)
                  UpperCamelCase__     : int											=					index + 1
            elif index + 1 == len(UpperCamelCase__		):
                  split_words.append(string[last_index : index + 1]		)
      return split_words


if __name__ == "__main__":
    from doctest import testmod

    testmod()


