






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




def        _lowerCAmelCase						(							UpperCAmelCase__    :   Dict=2,  UpperCAmelCase__    :   Tuple=3,  UpperCAmelCase__    :   List[Any]=1_6,  UpperCAmelCase__    :   int = 1_0,  UpperCAmelCase__    :   int = 2 )						->int:

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

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




def        _lowerCAmelCase						(							UpperCAmelCase__    :   Tuple,  UpperCAmelCase__    :   Any,  UpperCAmelCase__    :   List[Any],  UpperCAmelCase__    :   Any,  UpperCAmelCase__    :   Dict,  UpperCAmelCase__    :   Tuple=None )						->List[str]:
						A__  :					int											=					[]
						for epoch in range(UpperCAmelCase__ ):
												# Train quickly
												model.train()
												for batch in dataloader:
																		A__					,					A__  :					str											=					batch
																		A__  :					List[str]											=					model(UpperCAmelCase__ )
																		A__  :					List[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 							__SCREAMING_SNAKE_CASE  (			nn.Module						):


							def __init__(     self :  List[Any]							):
													'''simple docstring'''





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


							def   _UpperCamelCase    (     self :  Optional[Any]     ,      snake_case :  int							):
													'''simple docstring'''





													return x * self.a + self.b






class 							__SCREAMING_SNAKE_CASE  (			unittest.TestCase						):


							def   _UpperCamelCase    (     self :  List[Any]							):
													'''simple docstring'''





													with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(42							)
																			A__  :					Optional[Any]											=					DummyModel()
																			A__  :					int											=					torch.optim.Adam(params=model.parameters()     ,      lr=1e-3							)
																			A__					,					A__  :					Union[str, Any]											=					dummy_dataloaders()
																			A__  :					int											=					ProjectConfiguration(total_limit=1     ,      project_dir=snake_case     ,      automatic_checkpoint_naming=snake_case							)
																			# Train baseline
																			A__  :					Optional[Any]											=					Accelerator(project_config=snake_case							)
																			A__					,					A__					,					A__					,					A__  :					List[str]											=					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   _UpperCamelCase    (     self :  Any							):
													'''simple docstring'''





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

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

																			A__  :					Union[str, Any]											=					train(2     ,      snake_case     ,      snake_case     ,      snake_case     ,      snake_case							)
																			# Save everything
																			A__  :					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							)
																			((A__)					,					(A__))  :					int											=					model.a.item(), model.b.item()
																			A__  :					int											=					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   _UpperCamelCase    (     self :  Dict							):
													'''simple docstring'''





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

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

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

																			A__  :					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							)
																			((A__)					,					(A__))  :					Any											=					model.a.item(), model.b.item()
																			A__  :					Any											=					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   _UpperCamelCase    (     self :  List[str]							):
													'''simple docstring'''





													A__  :					Dict											=					torch.tensor([1, 2, 3]							)
													A__  :					Tuple											=					torch.tensor([2, 3, 4]							)
													A__  :					Union[str, Any]											=					DummyModel()
													A__  :					Optional[Any]											=					torch.optim.Adam(net.parameters()							)
													A__  :					str											=					Accelerator()
													with self.assertRaises(snake_case							) as ve:
																			accelerator.register_for_checkpointing(snake_case     ,      snake_case     ,      snake_case     ,      snake_case							)
													A__  :					str											=					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   _UpperCamelCase    (     self :  List[Any]							):
													'''simple docstring'''





													with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(42							)
																			A__  :					List[Any]											=					DummyModel()
																			A__  :					Union[str, Any]											=					torch.optim.Adam(params=model.parameters()     ,      lr=1e-3							)
																			A__  :					Optional[Any]											=					torch.optim.lr_scheduler.StepLR(snake_case     ,      step_size=1     ,      gamma=0.99							)
																			A__					,					A__  :					Optional[int]											=					dummy_dataloaders()
																			A__  :					List[Any]											=					ProjectConfiguration(automatic_checkpoint_naming=snake_case							)
																			# Train baseline
																			A__  :					Dict											=					Accelerator(project_dir=snake_case     ,      project_config=snake_case							)
																			A__					,					A__					,					A__					,					A__					,					A__  :					str											=					accelerator.prepare(
																			    snake_case     ,      snake_case     ,      snake_case     ,      snake_case     ,      snake_case							)
																			# Save initial
																			accelerator.save_state()
																			A__  :					int											=					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   _UpperCamelCase    (     self :  Union[str, Any]							):
													'''simple docstring'''





													with tempfile.TemporaryDirectory() as tmpdir:
																			set_seed(42							)
																			A__  :					Optional[int]											=					DummyModel()
																			A__  :					Optional[Any]											=					ProjectConfiguration(automatic_checkpoint_naming=snake_case     ,      total_limit=2							)
																			# Train baseline
																			A__  :					Optional[Any]											=					Accelerator(project_dir=snake_case     ,      project_config=snake_case							)
																			A__  :					Dict											=					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   _UpperCamelCase    (     self :  Tuple							):
													'''simple docstring'''





													A__  :					Optional[Any]											=					["""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__":
						A_      =							'''/tmp/accelerate/state_checkpointing'''
						A_      =							DummyModel()
						A_      =							torch.optim.Adam(params=model.parameters(), lr=1e-3)
						A_      =							torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
						A_      ,		A_      =							dummy_dataloaders()
						A_      =							ProjectConfiguration(automatic_checkpoint_naming=True)
						# Train baseline
						A_      =							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_      =							accelerator.prepare(
						    model, optimizer, train_dataloader, valid_dataloader, scheduler
						)
						A_      ,		A_      =							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_      =							group['''params'''][0].device
												break
						assert param_device.type == accelerator.device.type
						A_      =							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_      =							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_      =							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 os
from distutils.util import strtobool




def        _lowerCAmelCase						(							UpperCAmelCase__    :   List[Any],  UpperCAmelCase__    :   Optional[Any] )						->List[str]:
						for e in env_keys:
												A__  :					List[Any]											=					int(os.environ.get(UpperCAmelCase__,  -1 ) )
												if val >= 0:
																		return val
						return default




def        _lowerCAmelCase						(							UpperCAmelCase__    :   Tuple,  UpperCAmelCase__    :   str=False )						->List[str]:
						A__  :					List[Any]											=					os.environ.get(UpperCAmelCase__,  str(UpperCAmelCase__ ) )
						return strtobool(UpperCAmelCase__ ) == 1  # As its name indicates `strtobool` actually returns an int...




def        _lowerCAmelCase						(							UpperCAmelCase__    :   Tuple,  UpperCAmelCase__    :   List[Any]="no" )						->int:
						A__  :					str											=					os.environ.get(UpperCAmelCase__,  str(UpperCAmelCase__ ) )
						return value






