




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


UpperCAmelCase_									=	logging.getLogger(__name__)




def 					lowerCamelCase__       (						A__       :					Union[str, Any]=2  ,			A__       :					List[Any]=3  ,			A__       :					Optional[int]=16  ,			A__       :					int = 10  ,			A__       :					int = 2	):





       '''simple docstring'''



       def get_dataset(A__       :					Union[str, Any]	):
              __lowerCamelCase   =						torch.randn(batch_size * n_batches  ,			1	)
              return TensorDataset(A__  ,			a * x + b + 0.1 * torch.randn(batch_size * n_batches  ,			1	)	)

       __lowerCamelCase   =						get_dataset(A__	)
       __lowerCamelCase   =						get_dataset(A__	)
       __lowerCamelCase   =						DataLoader(A__  ,			shuffle=A__  ,			batch_size=A__  ,			num_workers=4	)
       __lowerCamelCase   =						DataLoader(A__  ,			shuffle=A__  ,			batch_size=A__  ,			num_workers=4	)
       return (train_dataloader, valid_dataloader)




def 					lowerCamelCase__       (						A__       :					List[str]  ,			A__       :					List[str]  ,			A__       :					Optional[Any]  ,			A__       :					Tuple  ,			A__       :					Dict  ,			A__       :					Union[str, Any]=None	):





       '''simple docstring'''



       __lowerCamelCase   =						[]
       for epoch in range(A__	):
              # Train quickly
              model.train()
              for batch in dataloader:
                     __lowerCamelCase,   __lowerCamelCase   =						batch
                     __lowerCamelCase   =						model(A__	)
                     __lowerCamelCase   =						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     lowerCamelCase__(					nn.Module):
      def __init__(				self: Dict   ):
             super().__init__()
             __lowerCamelCase   =						nn.Parameter(torch.randn(1   )   )
             __lowerCamelCase   =						nn.Parameter(torch.randn(1   )   )




      def 			lowerCAmelCase__						(				self: List[Any]    ,       UpperCamelCase_: Union[str, Any]   ):
             return x * self.a + self.b





class     lowerCamelCase__(					unittest.TestCase):
      def 			lowerCAmelCase__						(				self: int   ):
             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=UpperCamelCase_    ,       automatic_checkpoint_naming=UpperCamelCase_   )
                    # Train baseline
                    __lowerCamelCase   =						Accelerator(project_config=UpperCamelCase_   )
                    __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						accelerator.prepare(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    # Save initial
                    accelerator.save_state()

                    # Save second state
                    accelerator.save_state()
                    self.assertEqual(len(os.listdir(accelerator.project_dir   )   )    ,       1   )
      def 			lowerCAmelCase__						(				self: Optional[int]   ):
             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(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    # Save initial
                    __lowerCamelCase   =						os.path.join(UpperCamelCase_    ,       """initial"""   )
                    accelerator.save_state(UpperCamelCase_   )
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    __lowerCamelCase   =						train(3    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    ((__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(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    accelerator.load_state(UpperCamelCase_   )
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )

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

                    # Load everything back in and make sure all states work
                    accelerator.load_state(UpperCamelCase_   )
                    test_rands += train(1    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: List[str]   ):
             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=UpperCamelCase_   )

                    # Train baseline
                    __lowerCamelCase   =						Accelerator(project_dir=UpperCamelCase_    ,       project_config=UpperCamelCase_   )
                    __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						accelerator.prepare(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    # Save initial
                    accelerator.save_state()
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    __lowerCamelCase   =						train(3    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    ((__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=UpperCamelCase_   )
                    __lowerCamelCase   =						Accelerator(project_dir=UpperCamelCase_    ,       project_config=UpperCamelCase_   )
                    __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						accelerator.prepare(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    accelerator.load_state(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_0"""   )   )
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )

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

                    # Load everything back in and make sure all states work
                    accelerator.load_state(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_1"""   )   )
                    test_rands += train(1    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    ((__lowerCamelCase),   (__lowerCamelCase))   =						model.a.item(), model.b.item()
                    __lowerCamelCase   =						optimizer.state_dict()
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             __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(UpperCamelCase_   ) as ve:
                    accelerator.register_for_checkpointing(UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
             __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 			lowerCAmelCase__						(				self: Optional[int]   ):
             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(UpperCamelCase_    ,       step_size=1    ,       gamma=0.99   )
                    __lowerCamelCase,   __lowerCamelCase   =						dummy_dataloaders()
                    __lowerCamelCase   =						ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_   )
                    # Train baseline
                    __lowerCamelCase   =						Accelerator(project_dir=UpperCamelCase_    ,       project_config=UpperCamelCase_   )
                    __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase,   __lowerCamelCase   =						accelerator.prepare(
                        UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    # Save initial
                    accelerator.save_state()
                    __lowerCamelCase   =						scheduler.state_dict()
                    train(3    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertNotEqual(UpperCamelCase_    ,       scheduler.state_dict()   )

                    # Load everything back in and make sure all states work
                    accelerator.load_state(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_0"""   )   )
                    self.assertEqual(UpperCamelCase_    ,       scheduler.state_dict()   )
      def 			lowerCAmelCase__						(				self: Dict   ):
             with tempfile.TemporaryDirectory() as tmpdir:
                    set_seed(42   )
                    __lowerCamelCase   =						DummyModel()
                    __lowerCamelCase   =						ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_    ,       total_limit=2   )
                    # Train baseline
                    __lowerCamelCase   =						Accelerator(project_dir=UpperCamelCase_    ,       project_config=UpperCamelCase_   )
                    __lowerCamelCase   =						accelerator.prepare(UpperCamelCase_   )
                    # Save 3 states:
                    for _ in range(11   ):
                           accelerator.save_state()
                    self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_0"""   )   )   )
                    self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_9"""   )   )   )
                    self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_    ,       """checkpoints"""    ,       """checkpoint_10"""   )   )   )




      @require_cuda
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             __lowerCamelCase   =						["""torchrun""", F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__   )]
             execute_subprocess_async(UpperCamelCase_    ,       env=os.environ.copy()   )


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

import pytest

from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict


@dataclass
class        __UpperCamelCase				(						a__						):
							lowerCamelCase   :					List[str]      					=ComputeEnvironment.AMAZON_SAGEMAKER
							lowerCamelCase   :					str      					=True
							lowerCamelCase   :					Union[str, Any]      					="""ml.p3.2xlarge"""
							lowerCamelCase   :					str      					="""accelerate_sagemaker_execution_role"""
							lowerCamelCase   :					int      					="""hf-sm"""
							lowerCamelCase   :					int      					="""us-east-1"""
							lowerCamelCase   :					Tuple      					=1
							lowerCamelCase   :					Any      					="""accelerate-sagemaker-1"""
							lowerCamelCase   :					str      					="""1.6"""
							lowerCamelCase   :					Tuple      					="""4.4"""
							lowerCamelCase   :					Optional[int]      					="""train.py"""
							lowerCamelCase   :					Optional[Any]      					=[
							    """--model_name_or_path""",
							    """bert""",
							    """--do_train""",
							    """False""",
							    """--epochs""",
							    """3""",
							    """--learning_rate""",
							    """5e-5""",
							    """--max_steps""",
							    """50.5""",
							]
							lowerCamelCase   :					Union[str, Any]      					=[
							    """--model_name_or_path""",
							    """bert""",
							    """--do_train""",
							    """--do_test""",
							    """False""",
							    """--do_predict""",
							    """--epochs""",
							    """3""",
							    """--learning_rate""",
							    """5e-5""",
							    """--max_steps""",
							    """50.5""",
							]


class        __UpperCamelCase				(						unittest.TestCase						):






							def     __a   (   self      )	-> List[str]:
								# If no defaults are changed, `to_kwargs` returns an empty dict.
								a      :		str	=				_convert_nargs_to_dict(MockLaunchConfig.success_training_script_args      )
								assert isinstance(converted_args["model_name_or_path"]      ,					lowerCAmelCase__      )
								assert isinstance(converted_args["do_train"]      ,					lowerCAmelCase__      )
								assert isinstance(converted_args["epochs"]      ,					lowerCAmelCase__      )
								assert isinstance(converted_args["learning_rate"]      ,					lowerCAmelCase__      )
								assert isinstance(converted_args["max_steps"]      ,					lowerCAmelCase__      )

								with pytest.raises(lowerCAmelCase__      ):
									_convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args      )


