



"""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


__SCREAMING_SNAKE_CASE  :						str    							=      logging.getLogger(__name__)



def        lowerCAmelCase_(   lowercase_     :							Dict=2						,   lowercase_     :							Optional[int]=3						,   lowercase_     :							List[Any]=16						,   lowercase_     :							int = 10						,   lowercase_     :							int = 2							)	->       Dict:

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

    _lowerCamelCase        =				get_dataset(lowercase_							)
    _lowerCamelCase        =				get_dataset(lowercase_							)
    _lowerCamelCase        =				DataLoader(lowercase_						,   shuffle=lowercase_						,   batch_size=lowercase_						,   num_workers=4							)
    _lowerCamelCase        =				DataLoader(lowercase_						,   shuffle=lowercase_						,   batch_size=lowercase_						,   num_workers=4							)
    return (train_dataloader, valid_dataloader)



def        lowerCAmelCase_(   lowercase_     :							int						,   lowercase_     :							str						,   lowercase_     :							Any						,   lowercase_     :							str						,   lowercase_     :							Any						,   lowercase_     :							Tuple=None							)	->       Optional[Any]:
    _lowerCamelCase        =				[]
    for epoch in range(lowercase_							):
        # Train quickly
        model.train()
        for batch in dataloader:
            _lowerCamelCase  ,     _lowerCamelCase        =				batch
            _lowerCamelCase        =				model(lowercase_							)
            _lowerCamelCase        =				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   ):
         super().__init__()
         _lowerCamelCase        =				nn.Parameter(torch.randn(1   )   )
         _lowerCamelCase        =				nn.Parameter(torch.randn(1   )   )





     def 			snake_case__      (    self				,       lowerCamelCase__   ):
         return x * self.a + self.b


class 							lowerCamelCase_(   unittest.TestCase    ):





     '''simple docstring'''



     def 			snake_case__      (    self   ):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2   )
             _lowerCamelCase        =				DummyModel()
             _lowerCamelCase        =				torch.optim.Adam(params=model.parameters()				,       lr=1e-3   )
             _lowerCamelCase  ,     _lowerCamelCase        =				dummy_dataloaders()
             _lowerCamelCase        =				ProjectConfiguration(total_limit=1				,       project_dir=lowerCamelCase__				,       automatic_checkpoint_naming=lowerCamelCase__   )
             # Train baseline
             _lowerCamelCase        =				Accelerator(project_config=lowerCamelCase__   )
             _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase        =				accelerator.prepare(
                 lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             # Save initial
             accelerator.save_state()

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

     def 			snake_case__      (    self   ):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2   )
             _lowerCamelCase        =				DummyModel()
             _lowerCamelCase        =				torch.optim.Adam(params=model.parameters()				,       lr=1e-3   )
             _lowerCamelCase  ,     _lowerCamelCase        =				dummy_dataloaders()
             # Train baseline
             _lowerCamelCase        =				Accelerator()
             _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase        =				accelerator.prepare(
                 lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             # Save initial
             _lowerCamelCase        =				os.path.join(lowerCamelCase__				,       '''initial'''   )
             accelerator.save_state(lowerCamelCase__   )
             ((_lowerCamelCase)  ,     (_lowerCamelCase))        =				model.a.item(), model.b.item()
             _lowerCamelCase        =				optimizer.state_dict()
             _lowerCamelCase        =				train(3				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             ((_lowerCamelCase)  ,     (_lowerCamelCase))        =				model.a.item(), model.b.item()
             _lowerCamelCase        =				optimizer.state_dict()

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

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

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

     def 			snake_case__      (    self   ):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2   )
             _lowerCamelCase        =				DummyModel()
             _lowerCamelCase        =				torch.optim.Adam(params=model.parameters()				,       lr=1e-3   )
             _lowerCamelCase  ,     _lowerCamelCase        =				dummy_dataloaders()
             _lowerCamelCase        =				ProjectConfiguration(automatic_checkpoint_naming=lowerCamelCase__   )

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

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

             _lowerCamelCase        =				train(2				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             # Save everything
             accelerator.save_state()

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

     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				torch.tensor([1, 2, 3]   )
         _lowerCamelCase        =				torch.tensor([2, 3, 4]   )
         _lowerCamelCase        =				DummyModel()
         _lowerCamelCase        =				torch.optim.Adam(net.parameters()   )
         _lowerCamelCase        =				Accelerator()
         with self.assertRaises(lowerCamelCase__   ) as ve:
             accelerator.register_for_checkpointing(lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
         _lowerCamelCase        =				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   ):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2   )
             _lowerCamelCase        =				DummyModel()
             _lowerCamelCase        =				torch.optim.Adam(params=model.parameters()				,       lr=1e-3   )
             _lowerCamelCase        =				torch.optim.lr_scheduler.StepLR(lowerCamelCase__				,       step_size=1				,       gamma=0.9_9   )
             _lowerCamelCase  ,     _lowerCamelCase        =				dummy_dataloaders()
             _lowerCamelCase        =				ProjectConfiguration(automatic_checkpoint_naming=lowerCamelCase__   )
             # Train baseline
             _lowerCamelCase        =				Accelerator(project_dir=lowerCamelCase__				,       project_config=lowerCamelCase__   )
             _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase        =				accelerator.prepare(
                 lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             # Save initial
             accelerator.save_state()
             _lowerCamelCase        =				scheduler.state_dict()
             train(3				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__   )
             self.assertNotEqual(lowerCamelCase__				,       scheduler.state_dict()   )

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

     def 			snake_case__      (    self   ):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(4_2   )
             _lowerCamelCase        =				DummyModel()
             _lowerCamelCase        =				ProjectConfiguration(automatic_checkpoint_naming=lowerCamelCase__				,       total_limit=2   )
             # Train baseline
             _lowerCamelCase        =				Accelerator(project_dir=lowerCamelCase__				,       project_config=lowerCamelCase__   )
             _lowerCamelCase        =				accelerator.prepare(lowerCamelCase__   )
             # Save 3 states:
             for _ in range(1_1   ):
                 accelerator.save_state()
             self.assertTrue(not os.path.exists(os.path.join(lowerCamelCase__				,       '''checkpoints'''				,       '''checkpoint_0'''   )   )   )
             self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__				,       '''checkpoints'''				,       '''checkpoint_9'''   )   )   )
             self.assertTrue(os.path.exists(os.path.join(lowerCamelCase__				,       '''checkpoints'''				,       '''checkpoint_10'''   )   )   )





     @require_cuda
     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				['''torchrun''', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__   )]
         execute_subprocess_async(lowerCamelCase__				,       env=os.environ.copy()   )


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



def        lowerCAmelCase_(   lowercase_     :							np.array							)	->       np.array:
				return 1 / (1 + np.exp(-vector							))



def        lowerCAmelCase_(   lowercase_     :							np.array							)	->       np.array:
				return vector * sigmoid(1.7_0_2 * vector							)


if __name__ == "__main__":
			import doctest

			doctest.testmod()
