



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  UpperCAmelCase__    (    lowercase__=2						,       lowercase__=3						,       lowercase__=16						,       lowercase__ = 10						,       lowercase__ = 2   ) ->      List[Any]:

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

						__lowercase					=				get_dataset(lowercase__   )
						__lowercase					=				get_dataset(lowercase__   )
						__lowercase					=				DataLoader(lowercase__						,       shuffle=lowercase__						,       batch_size=lowercase__						,       num_workers=4   )
						__lowercase					=				DataLoader(lowercase__						,       shuffle=lowercase__						,       batch_size=lowercase__						,       num_workers=4   )
						return (train_dataloader, valid_dataloader)






def  UpperCAmelCase__    (    lowercase__						,       lowercase__						,       lowercase__						,       lowercase__						,       lowercase__						,       lowercase__=None   ) ->      Optional[int]:
						__lowercase					=				[]
						for epoch in range(lowercase__   ):
												# Train quickly
												model.train()
												for batch in dataloader:
																		__lowercase	,			__lowercase					=				batch
																		__lowercase					=				model(lowercase__   )
																		__lowercase					=				torch.nn.functional.mse_loss(lowercase__						,       lowercase__   )
																		accelerator.backward(lowercase__   )
																		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   )						->					int:
									"""simple docstring"""







									super().__init__()
									__lowercase					=				nn.Parameter(torch.randn(1   )   )
									__lowercase					=				nn.Parameter(torch.randn(1   )   )







			def 		snake_case__			(				self	:       Union[str, Any]			,     lowercase	:       Dict   )						->					Union[str, Any]:
									"""simple docstring"""







									return x * self.a + self.b





class 			_lowerCAmelCase   ( unittest.TestCase			):






			"""simple docstring"""





			def 		snake_case__			(				self	:       Optional[Any]   )						->					List[str]:
									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmpdir:
															set_seed(42   )
															__lowercase					=				DummyModel()
															__lowercase					=				torch.optim.Adam(params=model.parameters()			,     lr=1E-3   )
															__lowercase	,			__lowercase					=				dummy_dataloaders()
															__lowercase					=				ProjectConfiguration(total_limit=1			,     project_dir=lowercase			,     automatic_checkpoint_naming=lowercase   )
															# Train baseline
															__lowercase					=				Accelerator(project_config=lowercase   )
															__lowercase	,			__lowercase	,			__lowercase	,			__lowercase					=				accelerator.prepare(
															    lowercase			,     lowercase			,     lowercase			,     lowercase   )
															# Save initial
															accelerator.save_state()

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





			def 		snake_case__			(				self	:       Dict   )						->					str:
									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmpdir:
															set_seed(42   )
															__lowercase					=				DummyModel()
															__lowercase					=				torch.optim.Adam(params=model.parameters()			,     lr=1E-3   )
															__lowercase	,			__lowercase					=				dummy_dataloaders()
															# Train baseline
															__lowercase					=				Accelerator()
															__lowercase	,			__lowercase	,			__lowercase	,			__lowercase					=				accelerator.prepare(
															    lowercase			,     lowercase			,     lowercase			,     lowercase   )
															# Save initial
															__lowercase					=				os.path.join(lowercase			,     """initial"""   )
															accelerator.save_state(lowercase   )
															((__lowercase)	,			(__lowercase))					=				model.a.item(), model.b.item()
															__lowercase					=				optimizer.state_dict()
															__lowercase					=				train(3			,     lowercase			,     lowercase			,     lowercase			,     lowercase   )
															((__lowercase)	,			(__lowercase))					=				model.a.item(), model.b.item()
															__lowercase					=				optimizer.state_dict()

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

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

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





			def 		snake_case__			(				self	:       Optional[Any]   )						->					Tuple:
									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmpdir:
															set_seed(42   )
															__lowercase					=				DummyModel()
															__lowercase					=				torch.optim.Adam(params=model.parameters()			,     lr=1E-3   )
															__lowercase	,			__lowercase					=				dummy_dataloaders()
															__lowercase					=				ProjectConfiguration(automatic_checkpoint_naming=lowercase   )

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

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

															__lowercase					=				train(2			,     lowercase			,     lowercase			,     lowercase			,     lowercase   )
															# Save everything
															accelerator.save_state()

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





			def 		snake_case__			(				self	:       Tuple   )						->					List[str]:
									"""simple docstring"""







									__lowercase					=				torch.tensor([1, 2, 3]   )
									__lowercase					=				torch.tensor([2, 3, 4]   )
									__lowercase					=				DummyModel()
									__lowercase					=				torch.optim.Adam(net.parameters()   )
									__lowercase					=				Accelerator()
									with self.assertRaises(lowercase   ) as ve:
															accelerator.register_for_checkpointing(lowercase			,     lowercase			,     lowercase			,     lowercase   )
									__lowercase					=				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 		snake_case__			(				self	:       Optional[int]   )						->					int:
									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmpdir:
															set_seed(42   )
															__lowercase					=				DummyModel()
															__lowercase					=				torch.optim.Adam(params=model.parameters()			,     lr=1E-3   )
															__lowercase					=				torch.optim.lr_scheduler.StepLR(lowercase			,     step_size=1			,     gamma=0.99   )
															__lowercase	,			__lowercase					=				dummy_dataloaders()
															__lowercase					=				ProjectConfiguration(automatic_checkpoint_naming=lowercase   )
															# Train baseline
															__lowercase					=				Accelerator(project_dir=lowercase			,     project_config=lowercase   )
															__lowercase	,			__lowercase	,			__lowercase	,			__lowercase	,			__lowercase					=				accelerator.prepare(
															    lowercase			,     lowercase			,     lowercase			,     lowercase			,     lowercase   )
															# Save initial
															accelerator.save_state()
															__lowercase					=				scheduler.state_dict()
															train(3			,     lowercase			,     lowercase			,     lowercase			,     lowercase			,     lowercase   )
															self.assertNotEqual(lowercase			,     scheduler.state_dict()   )

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





			def 		snake_case__			(				self	:       Optional[int]   )						->					List[Any]:
									"""simple docstring"""







									with tempfile.TemporaryDirectory() as tmpdir:
															set_seed(42   )
															__lowercase					=				DummyModel()
															__lowercase					=				ProjectConfiguration(automatic_checkpoint_naming=lowercase			,     total_limit=2   )
															# Train baseline
															__lowercase					=				Accelerator(project_dir=lowercase			,     project_config=lowercase   )
															__lowercase					=				accelerator.prepare(lowercase   )
															# Save 3 states:
															for _ in range(11   ):
																					accelerator.save_state()
															self.assertTrue(not os.path.exists(os.path.join(lowercase			,     """checkpoints"""			,     """checkpoint_0"""   )   )   )
															self.assertTrue(os.path.exists(os.path.join(lowercase			,     """checkpoints"""			,     """checkpoint_9"""   )   )   )
															self.assertTrue(os.path.exists(os.path.join(lowercase			,     """checkpoints"""			,     """checkpoint_10"""   )   )   )







			@require_cuda
			def 		snake_case__			(				self	:       str   )						->					List[str]:
									"""simple docstring"""







									__lowercase					=				["""torchrun""", F"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__   )]
									execute_subprocess_async(lowercase			,     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()










import importlib
import os
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional, Union

import torch

from ..utils import BaseOutput


UpperCamelCase__ =						"scheduler_config.json"
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			lowercase__      :  List[Any]      =			1
			lowercase__      :  Tuple      =			2
			lowercase__      :  Union[str, Any]      =			3
			lowercase__      :  Union[str, Any]      =			4
			lowercase__      :  str      =			5
			lowercase__      :  Any      =			6
			lowercase__      :  Any      =			7
			lowercase__      :  List[str]      =			8
			lowercase__      :  Union[str, Any]      =			9
			lowercase__      :  int      =			10
			lowercase__      :  List[str]      =			11
			lowercase__      :  List[Any]      =			12
			lowercase__      :  str      =			13
			lowercase__      :  Optional[int]      =			14





@dataclass
class 			_lowerCAmelCase   ( _UpperCAmelCase			):






			"""simple docstring"""





			lowercase__      :  torch.FloatTensor





class 			_lowerCAmelCase   :






			"""simple docstring"""





			lowercase__      :  Optional[int]      =			SCHEDULER_CONFIG_NAME
			lowercase__      :  int      =			[]
			lowercase__      :  Dict      =			True





			@classmethod
			def 		snake_case__			(				cls	:       str			,     lowercase	:       Dict[str, Any] = None			,     lowercase	:       Optional[str] = None			,     lowercase	:       Any=False			,     **lowercase	:       List[str]			,     )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase	,			__lowercase	,			__lowercase					=				cls.load_config(
									    pretrained_model_name_or_path=lowercase			,     subfolder=lowercase			,     return_unused_kwargs=lowercase			,     return_commit_hash=lowercase			,     **lowercase			,     )
									return cls.from_config(lowercase			,     return_unused_kwargs=lowercase			,     **lowercase   )





			def 		snake_case__			(				self	:       Dict			,     lowercase	:       Union[str, os.PathLike]			,     lowercase	:       bool = False			,     **lowercase	:       List[str]   )						->					Optional[Any]:
									"""simple docstring"""







									self.save_config(save_directory=lowercase			,     push_to_hub=lowercase			,     **lowercase   )





			@property
			def 		snake_case__			(				self	:       Optional[Any]   )						->					Dict:
									"""simple docstring"""







									return self._get_compatibles()







			@classmethod
			def 		snake_case__			(				cls	:       List[str]   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				list(set([cls.__name__] + cls._compatibles   )   )
									__lowercase					=				importlib.import_module(__name__.split("""."""   )[0]   )
									__lowercase					=				[
									    getattr(lowercase			,     lowercase   ) for c in compatible_classes_str if hasattr(lowercase			,     lowercase   )
									]
									return compatible_classes





