



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 	lowerCamelCase_   (  _a    :		str=2					,						_a    :		Optional[int]=3					,						_a    :		List[str]=16					,						_a    :		int = 10					,						_a    :		int = 2  ):



    '''simple docstring'''




    def get_dataset(_a    :		Dict  ):
        UpperCAmelCase_			:    List[str]   						= torch.randn(batch_size * n_batches					,						1  )
        return TensorDataset(__lowerCAmelCase					,						a * x + b + 0.1 * torch.randn(batch_size * n_batches					,						1  )  )

    UpperCAmelCase_			:    int   						= get_dataset(__lowerCAmelCase  )
    UpperCAmelCase_			:    List[str]   						= get_dataset(__lowerCAmelCase  )
    UpperCAmelCase_			:    Optional[int]   						= DataLoader(__lowerCAmelCase					,						shuffle=__lowerCAmelCase					,						batch_size=__lowerCAmelCase					,						num_workers=4  )
    UpperCAmelCase_			:    Tuple   						= DataLoader(__lowerCAmelCase					,						shuffle=__lowerCAmelCase					,						batch_size=__lowerCAmelCase					,						num_workers=4  )
    return (train_dataloader, valid_dataloader)







def 	lowerCamelCase_   (  _a    :		Dict					,						_a    :		Union[str, Any]					,						_a    :		Tuple					,						_a    :		str					,						_a    :		int					,						_a    :		Optional[int]=None  ):



    '''simple docstring'''




    UpperCAmelCase_			:    Dict   						= []
    for epoch in range(__lowerCAmelCase  ):
        # Train quickly
        model.train()
        for batch in dataloader:
            UpperCAmelCase_						,      UpperCAmelCase_			:    List[str]   						= batch
            UpperCAmelCase_			:    Dict   						= 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:			Any				)     ->	Union[str, Any]:
       super().__init__()
       UpperCAmelCase_			:    Dict   						= nn.Parameter(torch.randn(1				)				)
       UpperCAmelCase_			:    List[str]   						= nn.Parameter(torch.randn(1				)				)






   def 	A__  (  self:			List[str]   ,lowerCamelCase_:			Union[str, Any]				)     ->	str:
       return x * self.a + self.b







class 	_snake_case							(			unittest.TestCase      ):






   '''simple docstring'''






   def 	A__  (  self:			Tuple				)     ->	Dict:
       with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42				)
           UpperCAmelCase_			:    Union[str, Any]   						= DummyModel()
           UpperCAmelCase_			:    List[str]   						= torch.optim.Adam(params=model.parameters()   ,lr=1e-3				)
           UpperCAmelCase_						,      UpperCAmelCase_			:    int   						= dummy_dataloaders()
           UpperCAmelCase_			:    Tuple   						= ProjectConfiguration(total_limit=1   ,project_dir=__snake_case   ,automatic_checkpoint_naming=__snake_case				)
           # Train baseline
           UpperCAmelCase_			:    Tuple   						= Accelerator(project_config=__snake_case				)
           UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_			:    Tuple   						= 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 	A__  (  self:			List[Any]				)     ->	str:
       with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42				)
           UpperCAmelCase_			:    List[Any]   						= DummyModel()
           UpperCAmelCase_			:    Union[str, Any]   						= torch.optim.Adam(params=model.parameters()   ,lr=1e-3				)
           UpperCAmelCase_						,      UpperCAmelCase_			:    Optional[int]   						= dummy_dataloaders()
           # Train baseline
           UpperCAmelCase_			:    Tuple   						= Accelerator()
           UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_			:    List[Any]   						= accelerator.prepare(
               __snake_case   ,__snake_case   ,__snake_case   ,__snake_case				)
           # Save initial
           UpperCAmelCase_			:    Dict   						= os.path.join(__snake_case   ,"""initial"""				)
           accelerator.save_state(__snake_case				)
           ((UpperCAmelCase_)						,      (UpperCAmelCase_))			:    Dict   						= model.a.item(), model.b.item()
           UpperCAmelCase_			:    Optional[Any]   						= optimizer.state_dict()
           UpperCAmelCase_			:    List[str]   						= train(3   ,__snake_case   ,__snake_case   ,__snake_case   ,__snake_case				)
           ((UpperCAmelCase_)						,      (UpperCAmelCase_))			:    List[Any]   						= model.a.item(), model.b.item()
           UpperCAmelCase_			:    Tuple   						= optimizer.state_dict()

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

           UpperCAmelCase_			:    Dict   						= train(2   ,__snake_case   ,__snake_case   ,__snake_case   ,__snake_case				)
           # Save everything
           UpperCAmelCase_			:    Optional[int]   						= 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				)
           ((UpperCAmelCase_)						,      (UpperCAmelCase_))			:    List[Any]   						= model.a.item(), model.b.item()
           UpperCAmelCase_			:    Any   						= 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 	A__  (  self:			str				)     ->	List[str]:
       with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42				)
           UpperCAmelCase_			:    Any   						= DummyModel()
           UpperCAmelCase_			:    Optional[int]   						= torch.optim.Adam(params=model.parameters()   ,lr=1e-3				)
           UpperCAmelCase_						,      UpperCAmelCase_			:    int   						= dummy_dataloaders()
           UpperCAmelCase_			:    str   						= ProjectConfiguration(automatic_checkpoint_naming=__snake_case				)

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

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

           UpperCAmelCase_			:    Union[str, Any]   						= 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				)
           ((UpperCAmelCase_)						,      (UpperCAmelCase_))			:    List[str]   						= model.a.item(), model.b.item()
           UpperCAmelCase_			:    Any   						= 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 	A__  (  self:			Union[str, Any]				)     ->	List[str]:
       UpperCAmelCase_			:    Optional[Any]   						= torch.tensor([1, 2, 3]				)
       UpperCAmelCase_			:    List[Any]   						= torch.tensor([2, 3, 4]				)
       UpperCAmelCase_			:    List[Any]   						= DummyModel()
       UpperCAmelCase_			:    Tuple   						= torch.optim.Adam(net.parameters()				)
       UpperCAmelCase_			:    Optional[Any]   						= Accelerator()
       with self.assertRaises(__snake_case				) as ve:
           accelerator.register_for_checkpointing(__snake_case   ,__snake_case   ,__snake_case   ,__snake_case				)
       UpperCAmelCase_			:    Dict   						= 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:			List[Any]				)     ->	Dict:
       with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42				)
           UpperCAmelCase_			:    Optional[Any]   						= DummyModel()
           UpperCAmelCase_			:    List[Any]   						= torch.optim.Adam(params=model.parameters()   ,lr=1e-3				)
           UpperCAmelCase_			:    List[str]   						= torch.optim.lr_scheduler.StepLR(__snake_case   ,step_size=1   ,gamma=0.9_9				)
           UpperCAmelCase_						,      UpperCAmelCase_			:    List[Any]   						= dummy_dataloaders()
           UpperCAmelCase_			:    int   						= ProjectConfiguration(automatic_checkpoint_naming=__snake_case				)
           # Train baseline
           UpperCAmelCase_			:    Optional[int]   						= Accelerator(project_dir=__snake_case   ,project_config=__snake_case				)
           UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_						,      UpperCAmelCase_			:    Optional[int]   						= accelerator.prepare(
               __snake_case   ,__snake_case   ,__snake_case   ,__snake_case   ,__snake_case				)
           # Save initial
           accelerator.save_state()
           UpperCAmelCase_			:    str   						= 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 	A__  (  self:			Optional[int]				)     ->	List[str]:
       with tempfile.TemporaryDirectory() as tmpdir:
           set_seed(42				)
           UpperCAmelCase_			:    Union[str, Any]   						= DummyModel()
           UpperCAmelCase_			:    List[Any]   						= ProjectConfiguration(automatic_checkpoint_naming=__snake_case   ,total_limit=2				)
           # Train baseline
           UpperCAmelCase_			:    Optional[int]   						= Accelerator(project_dir=__snake_case   ,project_config=__snake_case				)
           UpperCAmelCase_			:    Union[str, Any]   						= 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 	A__  (  self:			Dict				)     ->	str:
       UpperCAmelCase_			:    Dict   						= ["""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__":
      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.9_9)
      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_										=					accelerator.prepare(
          model, optimizer, train_dataloader, valid_dataloader, scheduler
      )
      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()




def 							__lowercase   ( __lowerCAmelCase							:				int					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float(moles / volume   ) * nfactor   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((moles * 0.0_821 * temperature) / (volume)   )   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((moles * 0.0_821 * temperature) / (pressure)   )   )






def 							__lowercase   ( __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float					,    __lowerCAmelCase							:				float   ):
							return round(float((pressure * volume) / (0.0_821 * moles)   )   )


if __name__ == "__main__":
						import doctest

						doctest.testmod()




