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


__lowerCAmelCase					: List[str]        =logging.getLogger(__name__)


def     UpperCAmelCase__ (       lowerCAmelCase__  :str=2      ,	lowerCAmelCase__  :Tuple=3      ,	lowerCAmelCase__  :int=1_6      ,	lowerCAmelCase__  :int = 1_0      ,	lowerCAmelCase__  :int = 2	)				->					List[Any]:
      '''simple docstring'''


      def get_dataset(lowerCAmelCase__  :List[Any]	):
            lowercase														=			torch.randn(batch_size * n_batches      ,	1	)
            return TensorDataset(lowerCAmelCase__      ,	a * x + b + 0.1 * torch.randn(batch_size * n_batches      ,	1	)	)

      lowercase														=			get_dataset(lowerCAmelCase__	)
      lowercase														=			get_dataset(lowerCAmelCase__	)
      lowercase														=			DataLoader(lowerCAmelCase__      ,	shuffle=lowerCAmelCase__      ,	batch_size=lowerCAmelCase__      ,	num_workers=4	)
      lowercase														=			DataLoader(lowerCAmelCase__      ,	shuffle=lowerCAmelCase__      ,	batch_size=lowerCAmelCase__      ,	num_workers=4	)
      return (train_dataloader, valid_dataloader)


def     UpperCAmelCase__ (       lowerCAmelCase__  :Optional[int]      ,	lowerCAmelCase__  :str      ,	lowerCAmelCase__  :Tuple      ,	lowerCAmelCase__  :Optional[Any]      ,	lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Tuple=None	)				->					Optional[Any]:
      '''simple docstring'''


      lowercase														=			[]
      for epoch in range(lowerCAmelCase__	):
            # Train quickly
            model.train()
            for batch in dataloader:
                  lowercase							,							lowercase														=			batch
                  lowercase														=			model(lowerCAmelCase__	)
                  lowercase														=			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 				_A		( nn.Module			):

      def __init__(		self		):







            """simple docstring"""



            super().__init__()
            lowercase														=			nn.Parameter(torch.randn(1		)		)
            lowercase														=			nn.Parameter(torch.randn(1		)		)







      def        A__ (		self	, __lowerCAmelCase		):







            """simple docstring"""



            return x * self.a + self.b






class 				_A		( unittest.TestCase			):

      def        A__ (		self		):







            """simple docstring"""



            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(42		)
                  lowercase														=			DummyModel()
                  lowercase														=			torch.optim.Adam(params=model.parameters()	, lr=1E-3		)
                  lowercase							,							lowercase														=			dummy_dataloaders()
                  lowercase														=			ProjectConfiguration(total_limit=1	, project_dir=__lowerCAmelCase	, automatic_checkpoint_naming=__lowerCAmelCase		)
                  # Train baseline
                  lowercase														=			Accelerator(project_config=__lowerCAmelCase		)
                  lowercase							,							lowercase							,							lowercase							,							lowercase														=			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        A__ (		self		):







            """simple docstring"""



            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(42		)
                  lowercase														=			DummyModel()
                  lowercase														=			torch.optim.Adam(params=model.parameters()	, lr=1E-3		)
                  lowercase							,							lowercase														=			dummy_dataloaders()
                  # Train baseline
                  lowercase														=			Accelerator()
                  lowercase							,							lowercase							,							lowercase							,							lowercase														=			accelerator.prepare(
                      __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
                  # Save initial
                  lowercase														=			os.path.join(__lowerCAmelCase	, """initial"""		)
                  accelerator.save_state(__lowerCAmelCase		)
                  ((lowercase)							,							(lowercase))														=			model.a.item(), model.b.item()
                  lowercase														=			optimizer.state_dict()
                  lowercase														=			train(3	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
                  ((lowercase)							,							(lowercase))														=			model.a.item(), model.b.item()
                  lowercase														=			optimizer.state_dict()

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

                  lowercase														=			train(2	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
                  # Save everything
                  lowercase														=			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		)
                  ((lowercase)							,							(lowercase))														=			model.a.item(), model.b.item()
                  lowercase														=			optimizer.state_dict()
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



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

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

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

                  lowercase														=			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		)
                  ((lowercase)							,							(lowercase))														=			model.a.item(), model.b.item()
                  lowercase														=			optimizer.state_dict()
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)
                  self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			torch.tensor([1, 2, 3]		)
            lowercase														=			torch.tensor([2, 3, 4]		)
            lowercase														=			DummyModel()
            lowercase														=			torch.optim.Adam(net.parameters()		)
            lowercase														=			Accelerator()
            with self.assertRaises(__lowerCAmelCase		) as ve:
                  accelerator.register_for_checkpointing(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
            lowercase														=			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		)
                  lowercase														=			DummyModel()
                  lowercase														=			torch.optim.Adam(params=model.parameters()	, lr=1E-3		)
                  lowercase														=			torch.optim.lr_scheduler.StepLR(__lowerCAmelCase	, step_size=1	, gamma=0.9_9		)
                  lowercase							,							lowercase														=			dummy_dataloaders()
                  lowercase														=			ProjectConfiguration(automatic_checkpoint_naming=__lowerCAmelCase		)
                  # Train baseline
                  lowercase														=			Accelerator(project_dir=__lowerCAmelCase	, project_config=__lowerCAmelCase		)
                  lowercase							,							lowercase							,							lowercase							,							lowercase							,							lowercase														=			accelerator.prepare(
                      __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
                  # Save initial
                  accelerator.save_state()
                  lowercase														=			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        A__ (		self		):







            """simple docstring"""



            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(42		)
                  lowercase														=			DummyModel()
                  lowercase														=			ProjectConfiguration(automatic_checkpoint_naming=__lowerCAmelCase	, total_limit=2		)
                  # Train baseline
                  lowercase														=			Accelerator(project_dir=__lowerCAmelCase	, project_config=__lowerCAmelCase		)
                  lowercase														=			accelerator.prepare(__lowerCAmelCase		)
                  # Save 3 states:
                  for _ in range(11		):
                        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        A__ (		self		):







            """simple docstring"""



            lowercase														=			["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__		)]
            execute_subprocess_async(__lowerCAmelCase	, env=os.environ.copy()		)


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






def     UpperCAmelCase__ (       lowerCAmelCase__  :int	)				->					bool:
      '''simple docstring'''


      lowercase														=			(1 + 2_4 * n) ** 0.5
      return ((1 + root) / 6) % 1 == 0


def     UpperCAmelCase__ (       lowerCAmelCase__  :int = 5_0_0_0	)				->					int:
      '''simple docstring'''


      lowercase														=			[(i * (3 * i - 1)) // 2 for i in range(1      ,	lowerCAmelCase__	)]
      for i, pentagonal_i in enumerate(lowerCAmelCase__	):
            for j in range(lowerCAmelCase__      ,	len(lowerCAmelCase__	)	):
                  lowercase														=			pentagonal_nums[j]
                  lowercase														=			pentagonal_i + pentagonal_j
                  lowercase														=			pentagonal_j - pentagonal_i
                  if is_pentagonal(lowerCAmelCase__	) and is_pentagonal(lowerCAmelCase__	):
                        return b

      return -1


if __name__ == "__main__":
       print(F"""{solution() = }""")



