






"""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__  ,  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__  ,  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__  ,  A__  ,  A__  ,  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__  ,  A__						:  Union[str, Any]		  =  dummy_dataloaders()
																			# Train baseline
																			A__						:  List[Any]		  =  Accelerator()
																			A__  ,  A__  ,  A__  ,  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__)  ,  (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__)  ,  (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__  ,  A__						:  Union[str, Any]		  =  dummy_dataloaders()
																			A__						:  Optional[int]		  =  Accelerator()
																			A__  ,  A__  ,  A__  ,  A__						:  Dict		  =  accelerator.prepare(
																			    snake_case			,    snake_case			,    snake_case			,    snake_case							)
																			accelerator.load_state(snake_case							)
																			((A__)  ,  (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__)  ,  (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__  ,  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__  ,  A__  ,  A__  ,  A__						:  Optional[int]		  =  accelerator.prepare(
																			    snake_case			,    snake_case			,    snake_case			,    snake_case							)
																			# Save initial
																			accelerator.save_state()
																			((A__)  ,  (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__)  ,  (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__  ,  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__  ,  A__  ,  A__  ,  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__)  ,  (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__)  ,  (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__  ,  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__  ,  A__  ,  A__  ,  A__  ,  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"""



def      _lowerCAmelCase		(							UpperCAmelCase__       :					str,						UpperCAmelCase__       :					List[Any]      )		->List[Any]:
						A__						:  Union[str, Any]		  =  [1]
						for i in range(2,						UpperCAmelCase__      ):
												factorials.append(factorials[-1] * i      )
						assert 0 <= k < factorials[-1] * n, "k out of bounds"

						A__						:  Optional[int]		  =  []
						A__						:  List[str]		  =  list(range(UpperCAmelCase__      )      )

						# Find permutation
						while factorials:
												A__						:  Optional[int]		  =  factorials.pop()
												A__  ,  A__						:  Optional[int]		  =  divmod(UpperCAmelCase__,						UpperCAmelCase__      )
												permutation.append(elements[number]      )
												elements.remove(elements[number]      )
						permutation.append(elements[0]      )

						return permutation


if __name__ == "__main__":
						import doctest

						doctest.testmod()






