



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


__lowerCamelCase         =			logging.getLogger(__name__)







def    _snake_case (       __snake_case=2					,  __snake_case=3					,  __snake_case=1_6					,  __snake_case = 1_0					,  __snake_case = 2    )     ->     Dict:






      '''simple docstring'''







      def get_dataset(__snake_case    ):
            UpperCAmelCase_  :	str				      =		torch.randn(batch_size * n_batches					,  1    )
            return TensorDataset(_lowerCAmelCase					,  a * x + b + 0.1 * torch.randn(batch_size * n_batches					,  1    )    )

      UpperCAmelCase_  :	Tuple				      =		get_dataset(_lowerCAmelCase    )
      UpperCAmelCase_  :	Union[str, Any]				      =		get_dataset(_lowerCAmelCase    )
      UpperCAmelCase_  :	int				      =		DataLoader(_lowerCAmelCase					,  shuffle=_lowerCAmelCase					,  batch_size=_lowerCAmelCase					,  num_workers=4    )
      UpperCAmelCase_  :	Union[str, Any]				      =		DataLoader(_lowerCAmelCase					,  shuffle=_lowerCAmelCase					,  batch_size=_lowerCAmelCase					,  num_workers=4    )
      return (train_dataloader, valid_dataloader)







def    _snake_case (       __snake_case					,  __snake_case					,  __snake_case					,  __snake_case					,  __snake_case					,  __snake_case=None    )     ->     Optional[Any]:






      '''simple docstring'''







      UpperCAmelCase_  :	List[str]				      =		[]
      for epoch in range(_lowerCAmelCase    ):
            # Train quickly
            model.train()
            for batch in dataloader:
                  UpperCAmelCase_  :	str				      =		batch
                  UpperCAmelCase_  :	int				      =		model(_lowerCAmelCase    )
                  UpperCAmelCase_  :	Tuple				      =		torch.nn.functional.mse_loss(_lowerCAmelCase					,  _lowerCAmelCase    )
                  accelerator.backward(_lowerCAmelCase    )
                  optimizer.step()
                  optimizer.zero_grad()
            rands.append(random.random()    )  # Introduce some randomness
            if scheduler is not None:
                  scheduler.step()
      return rands


class   snake_case_ (nn.Module  ):




       """simple docstring"""






       def __init__(     self):

             """simple docstring"""





             super().__init__()
             UpperCAmelCase_  :	int				      =		nn.Parameter(torch.randn(1))
             UpperCAmelCase_  :	int				      =		nn.Parameter(torch.randn(1))



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             return x * self.a + self.b


class   snake_case_ (unittest.TestCase  ):




       """simple docstring"""






       def  A_   (     self):

             """simple docstring"""





             with tempfile.TemporaryDirectory() as tmpdir:
                   set_seed(42)
                   UpperCAmelCase_  :	List[Any]				      =		DummyModel()
                   UpperCAmelCase_  :	List[str]				      =		torch.optim.Adam(params=model.parameters()     ,lr=1E-3)
                   UpperCAmelCase_  :	int				      =		dummy_dataloaders()
                   UpperCAmelCase_  :	Union[str, Any]				      =		ProjectConfiguration(total_limit=1     ,project_dir=A_     ,automatic_checkpoint_naming=A_)
                   # Train baseline
                   UpperCAmelCase_  :	Union[str, Any]				      =		Accelerator(project_config=A_)
                   UpperCAmelCase_  :	Dict				      =		accelerator.prepare(
                       A_     ,A_     ,A_     ,A_)
                   # Save initial
                   accelerator.save_state()

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



       def  A_   (     self):

             """simple docstring"""





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

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

                   UpperCAmelCase_  :	Tuple				      =		train(2     ,A_     ,A_     ,A_     ,A_)
                   # Save everything
                   UpperCAmelCase_  :	Optional[int]				      =		os.path.join(A_     ,"checkpoint")
                   accelerator.save_state(A_)

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



       def  A_   (     self):

             """simple docstring"""





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

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

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

                   UpperCAmelCase_  :	str				      =		train(2     ,A_     ,A_     ,A_     ,A_)
                   # Save everything
                   accelerator.save_state()

                   # Load everything back in and make sure all states work
                   accelerator.load_state(os.path.join(A_     ,"checkpoints"     ,"checkpoint_1"))
                   test_rands += train(1     ,A_     ,A_     ,A_     ,A_)
                   (UpperCAmelCase_)  :	List[str]				      =		model.a.item(), model.b.item()
                   UpperCAmelCase_  :	Any				      =		optimizer.state_dict()
                   self.assertEqual(A_     ,A_)
                   self.assertEqual(A_     ,A_)
                   self.assertEqual(A_     ,A_)
                   self.assertEqual(A_     ,A_)



       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	str				      =		torch.tensor([1, 2, 3])
             UpperCAmelCase_  :	Any				      =		torch.tensor([2, 3, 4])
             UpperCAmelCase_  :	Dict				      =		DummyModel()
             UpperCAmelCase_  :	Union[str, Any]				      =		torch.optim.Adam(net.parameters())
             UpperCAmelCase_  :	List[str]				      =		Accelerator()
             with self.assertRaises(A_) as ve:
                   accelerator.register_for_checkpointing(A_     ,A_     ,A_     ,A_)
             UpperCAmelCase_  :	List[str]				      =		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  A_   (     self):

             """simple docstring"""





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

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



       def  A_   (     self):

             """simple docstring"""





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



       @require_cuda
       def  A_   (     self):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)]
             execute_subprocess_async(A_     ,env=os.environ.copy())


if __name__ == "__main__":
   __lowerCamelCase         =			"""/tmp/accelerate/state_checkpointing"""
   __lowerCamelCase         =			DummyModel()
   __lowerCamelCase         =			torch.optim.Adam(params=model.parameters(), lr=1e-3)
   __lowerCamelCase         =			torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9)
   __lowerCamelCase         =			dummy_dataloaders()
   __lowerCamelCase         =			ProjectConfiguration(automatic_checkpoint_naming=True)
   # Train baseline
   __lowerCamelCase         =			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)
   __lowerCamelCase         =			accelerator.prepare(
       model, optimizer, train_dataloader, valid_dataloader, scheduler
   )
   __lowerCamelCase         =			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:
      __lowerCamelCase         =			group["""params"""][0].device
      break
   assert param_device.type == accelerator.device.type
   __lowerCamelCase         =			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:
      __lowerCamelCase         =			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:
      __lowerCamelCase         =			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()





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
   import torch


class   snake_case_ (TensorFormatter[Mapping, """torch.Tensor""", Mapping]  ):




       """simple docstring"""






       def __init__(     self     ,lowercase=None     ,**lowercase):

             """simple docstring"""





             super().__init__(features=lowercase)
             UpperCAmelCase_  :	Union[str, Any]				      =		torch_tensor_kwargs
             import torch  # noqa import torch at initialization



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             if isinstance(lowercase     ,lowercase) and column:
                   if all(
                       isinstance(lowercase     ,torch.Tensor) and x.shape == column[0].shape and x.dtype == column[0].dtype
                       for x in column):
                         return torch.stack(lowercase)
             return column



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             if isinstance(lowercase     ,(str, bytes, type(lowercase))):
                   return value
             elif isinstance(lowercase     ,(np.character, np.ndarray)) and np.issubdtype(value.dtype     ,np.character):
                   return value.tolist()

             UpperCAmelCase_  :	List[str]				      =		{}

             if isinstance(lowercase     ,(np.number, np.ndarray)) and np.issubdtype(value.dtype     ,np.integer):
                   UpperCAmelCase_  :	Dict				      =		{"dtype": torch.intaa}
             elif isinstance(lowercase     ,(np.number, np.ndarray)) and np.issubdtype(value.dtype     ,np.floating):
                   UpperCAmelCase_  :	Optional[Any]				      =		{"dtype": torch.floataa}
             elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                   import PIL.Image

                   if isinstance(lowercase     ,PIL.Image.Image):
                         UpperCAmelCase_  :	List[str]				      =		np.asarray(lowercase)
             return torch.tensor(lowercase     ,**{**default_dtype, **self.torch_tensor_kwargs})



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             import torch

             # support for torch, tf, jax etc.
             if hasattr(lowercase     ,"__array__") and not isinstance(lowercase     ,torch.Tensor):
                   UpperCAmelCase_  :	int				      =		data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(lowercase     ,np.ndarray):
                   if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                         return self._consolidate([self.recursive_tensorize(lowercase) for substruct in data_struct])
             elif isinstance(lowercase     ,(list, tuple)):
                   return self._consolidate([self.recursive_tensorize(lowercase) for substruct in data_struct])
             return self._tensorize(lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             return map_nested(self._recursive_tensorize     ,lowercase     ,map_list=lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	List[Any]				      =		self.numpy_arrow_extractor().extract_row(lowercase)
             UpperCAmelCase_  :	Tuple				      =		self.python_features_decoder.decode_row(lowercase)
             return self.recursive_tensorize(lowercase)



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	str				      =		self.numpy_arrow_extractor().extract_column(lowercase)
             UpperCAmelCase_  :	List[Any]				      =		self.python_features_decoder.decode_column(lowercase     ,pa_table.column_names[0])
             UpperCAmelCase_  :	List[Any]				      =		self.recursive_tensorize(lowercase)
             UpperCAmelCase_  :	List[str]				      =		self._consolidate(lowercase)
             return column



       def  A_   (     self     ,lowercase):

             """simple docstring"""





             UpperCAmelCase_  :	Any				      =		self.numpy_arrow_extractor().extract_batch(lowercase)
             UpperCAmelCase_  :	Optional[int]				      =		self.python_features_decoder.decode_batch(lowercase)
             UpperCAmelCase_  :	List[Any]				      =		self.recursive_tensorize(lowercase)
             for column_name in batch:
                   UpperCAmelCase_  :	Optional[int]				      =		self._consolidate(batch[column_name])
             return batch
