






"""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__       :					Any=2,						UpperCAmelCase__       :					str=3,						UpperCAmelCase__       :					int=1_6,						UpperCAmelCase__       :					int = 1_0,						UpperCAmelCase__       :					int = 2      )		->List[str]:

						def get_dataset(UpperCAmelCase__       :					int      ):
												A__						:  Tuple		  =  torch.randn(batch_size * n_batches,						1      )
												return TensorDataset(UpperCAmelCase__,						a * x + b + 0.1 * torch.randn(batch_size * n_batches,						1      )      )

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




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





													super().__init__()
													A__						:  Dict		  =  nn.Parameter(torch.randn(1							)							)
													A__						:  str		  =  nn.Parameter(torch.randn(1							)							)


							def 						_UpperCamelCase       (			self      :						Union[str, Any]			,    snake_case      :						Any							):
													'''simple docstring'''





													return x * self.a + self.b






class 							__SCREAMING_SNAKE_CASE						(				unittest.TestCase		):


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





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





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

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

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





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

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

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

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





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





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





													A__						:  Union[str, 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"""



from .integrations import (
    is_optuna_available,
    is_ray_available,
    is_sigopt_available,
    is_wandb_available,
    run_hp_search_optuna,
    run_hp_search_ray,
    run_hp_search_sigopt,
    run_hp_search_wandb,
)
from .trainer_utils import (
    HPSearchBackend,
    default_hp_space_optuna,
    default_hp_space_ray,
    default_hp_space_sigopt,
    default_hp_space_wandb,
)
from .utils import logging


A_    =							logging.get_logger(__name__)






class 							__SCREAMING_SNAKE_CASE						:
							snake_case_     =							42
							snake_case_     =							None


							@staticmethod
							def 						_UpperCamelCase       (			):
													'''simple docstring'''





													raise NotImplementedError


							def 						_UpperCamelCase       (			self      :						str			,    snake_case      :						int			,    snake_case      :						int			,    snake_case      :						str			,    **snake_case      :						Any							):
													'''simple docstring'''





													raise NotImplementedError


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





													raise NotImplementedError


							def 						_UpperCamelCase       (			self      :						Union[str, Any]							):
													'''simple docstring'''





													if not self.is_available():
																			raise RuntimeError(
																			    F'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.'							)


							@classmethod
							def 						_UpperCamelCase       (			cls      :						Optional[int]							):
													'''simple docstring'''





													return F'`pip install {cls.pip_package or cls.name}`'






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							'optuna'


							@staticmethod
							def 						_UpperCamelCase       (			):
													'''simple docstring'''





													return is_optuna_available()


							def 						_UpperCamelCase       (			self      :						str			,    snake_case      :						str			,    snake_case      :						int			,    snake_case      :						str			,    **snake_case      :						Any							):
													'''simple docstring'''





													return run_hp_search_optuna(snake_case			,    snake_case			,    snake_case			,    **snake_case							)


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





													return default_hp_space_optuna(snake_case							)






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							'ray'
							snake_case_     =							'\'ray[tune]\''


							@staticmethod
							def 						_UpperCamelCase       (			):
													'''simple docstring'''





													return is_ray_available()


							def 						_UpperCamelCase       (			self      :						Any			,    snake_case      :						Tuple			,    snake_case      :						int			,    snake_case      :						str			,    **snake_case      :						List[Any]							):
													'''simple docstring'''





													return run_hp_search_ray(snake_case			,    snake_case			,    snake_case			,    **snake_case							)


							def 						_UpperCamelCase       (			self      :						Dict			,    snake_case      :						Dict							):
													'''simple docstring'''





													return default_hp_space_ray(snake_case							)






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							'sigopt'


							@staticmethod
							def 						_UpperCamelCase       (			):
													'''simple docstring'''





													return is_sigopt_available()


							def 						_UpperCamelCase       (			self      :						str			,    snake_case      :						str			,    snake_case      :						int			,    snake_case      :						str			,    **snake_case      :						Union[str, Any]							):
													'''simple docstring'''





													return run_hp_search_sigopt(snake_case			,    snake_case			,    snake_case			,    **snake_case							)


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





													return default_hp_space_sigopt(snake_case							)






class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase		):
							snake_case_     =							'wandb'


							@staticmethod
							def 						_UpperCamelCase       (			):
													'''simple docstring'''





													return is_wandb_available()


							def 						_UpperCamelCase       (			self      :						int			,    snake_case      :						int			,    snake_case      :						int			,    snake_case      :						str			,    **snake_case      :						Any							):
													'''simple docstring'''





													return run_hp_search_wandb(snake_case			,    snake_case			,    snake_case			,    **snake_case							)


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





													return default_hp_space_wandb(snake_case							)




A_    =							{
    HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}




def      _lowerCAmelCase		(							)		->str:
						A__						:  List[Any]		  =  [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
						if len(UpperCAmelCase__      ) > 0:
												A__						:  Dict		  =  available_backends[0].name
												if len(UpperCAmelCase__      ) > 1:
																		logger.info(
																		    f'{len(UpperCAmelCase__      )} hyperparameter search backends available. Using {name} as the default.'      )
												return name
						raise RuntimeError(
						    """No hyperparameter search backend available.\n"""
						    + """\n""".join(
						        f' - To install {backend.name} run {backend.pip_install()}'
						        for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()      )      )






