





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							:			List[Any]         =			logging.getLogger(__name__)





def 				__lowerCAmelCase(       _SCREAMING_SNAKE_CASE=2							,     _SCREAMING_SNAKE_CASE=3							,     _SCREAMING_SNAKE_CASE=16							,     _SCREAMING_SNAKE_CASE = 10							,     _SCREAMING_SNAKE_CASE = 2				)							-> List[Any]:




    """simple docstring"""




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

    _A     =							get_dataset(_SCREAMING_SNAKE_CASE				)
    _A     =							get_dataset(_SCREAMING_SNAKE_CASE				)
    _A     =							DataLoader(_SCREAMING_SNAKE_CASE							,     shuffle=_SCREAMING_SNAKE_CASE							,     batch_size=_SCREAMING_SNAKE_CASE							,     num_workers=4				)
    _A     =							DataLoader(_SCREAMING_SNAKE_CASE							,     shuffle=_SCREAMING_SNAKE_CASE							,     batch_size=_SCREAMING_SNAKE_CASE							,     num_workers=4				)
    return (train_dataloader, valid_dataloader)





def 				__lowerCAmelCase(       _SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE=None				)							-> Any:




    """simple docstring"""




    _A     =							[]
    for epoch in range(_SCREAMING_SNAKE_CASE				):
        # Train quickly
        model.train()
        for batch in dataloader:
            _A,			_A     =							batch
            _A     =							model(_SCREAMING_SNAKE_CASE				)
            _A     =							torch.nn.functional.mse_loss(_SCREAMING_SNAKE_CASE							,     _SCREAMING_SNAKE_CASE				)
            accelerator.backward(_SCREAMING_SNAKE_CASE				)
            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__()
         _A     =							nn.Parameter(torch.randn(1							)							)
         _A     =							nn.Parameter(torch.randn(1							)							)




     def        lowerCAmelCase__		(    self				,     snake_case_							):
         return x * self.a + self.b







class      lowerCamelCase(						unittest.TestCase	):
     '''simple docstring'''


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

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

             _A     =							train(2				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							)
             # Save everything
             _A     =							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))     =							model.a.item(), model.b.item()
             _A     =							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        lowerCAmelCase__		(    self							):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(42							)
             _A     =							DummyModel()
             _A     =							torch.optim.Adam(params=model.parameters()				,     lr=1E-3							)
             _A,			_A     =							dummy_dataloaders()
             _A     =							ProjectConfiguration(automatic_checkpoint_naming=snake_case_							)

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

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

             _A     =							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))     =							model.a.item(), model.b.item()
             _A     =							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        lowerCAmelCase__		(    self							):
         _A     =							torch.tensor([1, 2, 3]							)
         _A     =							torch.tensor([2, 3, 4]							)
         _A     =							DummyModel()
         _A     =							torch.optim.Adam(net.parameters()							)
         _A     =							Accelerator()
         with self.assertRaises(snake_case_							) as ve:
             accelerator.register_for_checkpointing(snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							)
         _A     =							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        lowerCAmelCase__		(    self							):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(42							)
             _A     =							DummyModel()
             _A     =							torch.optim.Adam(params=model.parameters()				,     lr=1E-3							)
             _A     =							torch.optim.lr_scheduler.StepLR(snake_case_				,     step_size=1				,     gamma=0.99							)
             _A,			_A     =							dummy_dataloaders()
             _A     =							ProjectConfiguration(automatic_checkpoint_naming=snake_case_							)
             # Train baseline
             _A     =							Accelerator(project_dir=snake_case_				,     project_config=snake_case_							)
             _A,			_A,			_A,			_A,			_A     =							accelerator.prepare(
                 snake_case_				,     snake_case_				,     snake_case_				,     snake_case_				,     snake_case_							)
             # Save initial
             accelerator.save_state()
             _A     =							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        lowerCAmelCase__		(    self							):
         with tempfile.TemporaryDirectory() as tmpdir:
             set_seed(42							)
             _A     =							DummyModel()
             _A     =							ProjectConfiguration(automatic_checkpoint_naming=snake_case_				,     total_limit=2							)
             # Train baseline
             _A     =							Accelerator(project_dir=snake_case_				,     project_config=snake_case_							)
             _A     =							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        lowerCAmelCase__		(    self							):
         _A     =							['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							:			Tuple         =			"/tmp/accelerate/state_checkpointing"
 __A							:			List[str]         =			DummyModel()
 __A							:			Union[str, Any]         =			torch.optim.Adam(params=model.parameters(), lr=1E-3)
 __A							:			Optional[Any]         =			torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9)
 __A     ,						__A							:			Dict         =			dummy_dataloaders()
 __A							:			Any         =			ProjectConfiguration(automatic_checkpoint_naming=True)
 # Train baseline
 __A							:			Optional[Any]         =			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							:			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							:			Optional[int]         =			group["params"][0].device
  break
 assert param_device.type == accelerator.device.type
 __A							:			str         =			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							:			int         =			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							:			Tuple         =			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 numpy as np





def 				__lowerCAmelCase(       _SCREAMING_SNAKE_CASE				)							-> np.array:




    """simple docstring"""




    return (2 / (1 + np.exp(-2 * vector				))) - 1


if __name__ == "__main__":
 import doctest

 doctest.testmod()





