






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






def 				lowerCamelCase__				(_UpperCAmelCase=2							,       _UpperCAmelCase=3							,       _UpperCAmelCase=16							,       _UpperCAmelCase = 10							,       _UpperCAmelCase = 2):

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

			SCREAMING_SNAKE_CASE						= get_dataset(_UpperCAmelCase)
			SCREAMING_SNAKE_CASE						= get_dataset(_UpperCAmelCase)
			SCREAMING_SNAKE_CASE						= DataLoader(_UpperCAmelCase							,       shuffle=_UpperCAmelCase							,       batch_size=_UpperCAmelCase							,       num_workers=4)
			SCREAMING_SNAKE_CASE						= DataLoader(_UpperCAmelCase							,       shuffle=_UpperCAmelCase							,       batch_size=_UpperCAmelCase							,       num_workers=4)
			return (train_dataloader, valid_dataloader)






def 				lowerCamelCase__				(_UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase							,       _UpperCAmelCase=None):
			SCREAMING_SNAKE_CASE						= []
			for epoch in range(_UpperCAmelCase):
						# Train quickly
						model.train()
						for batch in dataloader:
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= batch
									SCREAMING_SNAKE_CASE						= model(_UpperCAmelCase)
									SCREAMING_SNAKE_CASE						= 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 		_snake_case  (  nn.Module					):






			def __init__(       self)      ->       List[Any]:
						super().__init__()
						SCREAMING_SNAKE_CASE						= nn.Parameter(torch.randn(1))
						SCREAMING_SNAKE_CASE						= nn.Parameter(torch.randn(1))







			def    SCREAMING_SNAKE_CASE__    (       self		,					a)      ->       Tuple:
						return x * self.a + self.b



class 		_snake_case  (  unittest.TestCase					):






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
						with tempfile.TemporaryDirectory() as tmpdir:
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									SCREAMING_SNAKE_CASE						= ProjectConfiguration(total_limit=1		,					project_dir=a		,					automatic_checkpoint_naming=a)
									# Train baseline
									SCREAMING_SNAKE_CASE						= Accelerator(project_config=a)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a)
									# 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)      ->       int:
						with tempfile.TemporaryDirectory() as tmpdir:
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									# Train baseline
									SCREAMING_SNAKE_CASE						= Accelerator()
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a)
									# Save initial
									SCREAMING_SNAKE_CASE						= os.path.join(a		,					'initial')
									accelerator.save_state(a)
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()
									SCREAMING_SNAKE_CASE						= train(3		,					a		,					a		,					a		,					a)
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()

									# Train partially
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									SCREAMING_SNAKE_CASE						= Accelerator()
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a)
									accelerator.load_state(a)
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()
									self.assertEqual(a		,					a)
									self.assertEqual(a		,					a)
									self.assertEqual(a		,					a)

									SCREAMING_SNAKE_CASE						= train(2		,					a		,					a		,					a		,					a)
									# Save everything
									SCREAMING_SNAKE_CASE						= os.path.join(a		,					'checkpoint')
									accelerator.save_state(a)

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






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						with tempfile.TemporaryDirectory() as tmpdir:
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									SCREAMING_SNAKE_CASE						= ProjectConfiguration(automatic_checkpoint_naming=a)

									# Train baseline
									SCREAMING_SNAKE_CASE						= Accelerator(project_dir=a		,					project_config=a)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a)
									# Save initial
									accelerator.save_state()
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()
									SCREAMING_SNAKE_CASE						= train(3		,					a		,					a		,					a		,					a)
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()

									# Train partially
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									SCREAMING_SNAKE_CASE						= ProjectConfiguration(iteration=1		,					automatic_checkpoint_naming=a)
									SCREAMING_SNAKE_CASE						= Accelerator(project_dir=a		,					project_config=a)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a)
									accelerator.load_state(os.path.join(a		,					'checkpoints'		,					'checkpoint_0'))
									((SCREAMING_SNAKE_CASE)				,						(SCREAMING_SNAKE_CASE))						= model.a.item(), model.b.item()
									SCREAMING_SNAKE_CASE						= optimizer.state_dict()
									self.assertEqual(a		,					a)
									self.assertEqual(a		,					a)
									self.assertEqual(a		,					a)

									SCREAMING_SNAKE_CASE						= train(2		,					a		,					a		,					a		,					a)
									# Save everything
									accelerator.save_state()

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






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Optional[int]:
						SCREAMING_SNAKE_CASE						= torch.tensor([1, 2, 3])
						SCREAMING_SNAKE_CASE						= torch.tensor([2, 3, 4])
						SCREAMING_SNAKE_CASE						= DummyModel()
						SCREAMING_SNAKE_CASE						= torch.optim.Adam(net.parameters())
						SCREAMING_SNAKE_CASE						= Accelerator()
						with self.assertRaises(a) as ve:
									accelerator.register_for_checkpointing(a		,					a		,					a		,					a)
						SCREAMING_SNAKE_CASE						= 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)      ->       List[str]:
						with tempfile.TemporaryDirectory() as tmpdir:
									set_seed(42)
									SCREAMING_SNAKE_CASE						= DummyModel()
									SCREAMING_SNAKE_CASE						= torch.optim.Adam(params=model.parameters()		,					lr=1E-3)
									SCREAMING_SNAKE_CASE						= torch.optim.lr_scheduler.StepLR(a		,					step_size=1		,					gamma=0.99)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= dummy_dataloaders()
									SCREAMING_SNAKE_CASE						= ProjectConfiguration(automatic_checkpoint_naming=a)
									# Train baseline
									SCREAMING_SNAKE_CASE						= Accelerator(project_dir=a		,					project_config=a)
									SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						= accelerator.prepare(
									    a		,					a		,					a		,					a		,					a)
									# Save initial
									accelerator.save_state()
									SCREAMING_SNAKE_CASE						= scheduler.state_dict()
									train(3		,					a		,					a		,					a		,					a		,					a)
									self.assertNotEqual(a		,					scheduler.state_dict())

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






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







			@require_cuda
			def    SCREAMING_SNAKE_CASE__    (       self)      ->       List[Any]:
						SCREAMING_SNAKE_CASE						= ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__)]
						execute_subprocess_async(a		,					env=os.environ.copy())


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












import unittest

from accelerate import debug_launcher
from accelerate.test_utils import require_cpu, test_ops, test_script

@require_cpu
class 		_snake_case  (  unittest.TestCase					):






			def    SCREAMING_SNAKE_CASE__    (       self)      ->       str:
						debug_launcher(test_script.main)







			def    SCREAMING_SNAKE_CASE__    (       self)      ->       Any:
						debug_launcher(test_ops.main)




