
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


lowercase_ 				=			logging.getLogger(__name__)


def 							a__					(							snake_case=2       ,			snake_case=3       ,			snake_case=16       ,			snake_case = 10       ,			snake_case = 2							):





  """simple docstring"""

  def get_dataset(snake_case							):
    __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		torch.randn(batch_size * n_batches       ,			1							)
    return TensorDataset(snake_case       ,			a * x + b + 0.1 * torch.randn(batch_size * n_batches       ,			1							)							)

  __SCREAMING_SNAKE_CASE      :	str					=		get_dataset(snake_case							)
  __SCREAMING_SNAKE_CASE      :	Dict					=		get_dataset(snake_case							)
  __SCREAMING_SNAKE_CASE      :	Optional[int]					=		DataLoader(snake_case       ,			shuffle=snake_case       ,			batch_size=snake_case       ,			num_workers=4							)
  __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		DataLoader(snake_case       ,			shuffle=snake_case       ,			batch_size=snake_case       ,			num_workers=4							)
  return (train_dataloader, valid_dataloader)


def 							a__					(							snake_case       ,			snake_case       ,			snake_case       ,			snake_case       ,			snake_case       ,			snake_case=None							):





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





class     __UpperCamelCase (							nn.Module       ):






     """simple docstring"""







     def __init__(				self							:							Union[str, Any] ):







       """simple docstring"""




       super().__init__()
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		nn.Parameter(torch.randn(1 ) )
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		nn.Parameter(torch.randn(1 ) )




     def  UpperCAmelCase__							(				self							:							Union[str, Any]     ,						_A							:							List[str] ):







       """simple docstring"""




       return x * self.a + self.b






class     __UpperCamelCase (							unittest.TestCase       ):






     """simple docstring"""







     def  UpperCAmelCase__							(				self							:							Any ):







       """simple docstring"""




       with tempfile.TemporaryDirectory() as tmpdir:
         set_seed(42 )
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		DummyModel()
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		torch.optim.Adam(params=model.parameters()     ,						lr=1e-3 )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	List[str]					=		dummy_dataloaders()
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		ProjectConfiguration(total_limit=1     ,						project_dir=_A     ,						automatic_checkpoint_naming=_A )
         # Train baseline
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		Accelerator(project_config=_A )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	List[Any]					=		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  UpperCAmelCase__							(				self							:							List[str] ):







       """simple docstring"""




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

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

         __SCREAMING_SNAKE_CASE      :	Tuple					=		train(2     ,						_A     ,						_A     ,						_A     ,						_A )
         # Save everything
         __SCREAMING_SNAKE_CASE      :	Dict					=		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 )
         ((__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE))      :	Tuple					=		model.a.item(), model.b.item()
         __SCREAMING_SNAKE_CASE      :	str					=		optimizer.state_dict()
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )



     def  UpperCAmelCase__							(				self							:							int ):







       """simple docstring"""




       with tempfile.TemporaryDirectory() as tmpdir:
         set_seed(42 )
         __SCREAMING_SNAKE_CASE      :	List[str]					=		DummyModel()
         __SCREAMING_SNAKE_CASE      :	List[str]					=		torch.optim.Adam(params=model.parameters()     ,						lr=1e-3 )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	str					=		dummy_dataloaders()
         __SCREAMING_SNAKE_CASE      :	Tuple					=		ProjectConfiguration(automatic_checkpoint_naming=_A )

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

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

         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		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 )
         ((__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE))      :	Optional[int]					=		model.a.item(), model.b.item()
         __SCREAMING_SNAKE_CASE      :	int					=		optimizer.state_dict()
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )
         self.assertEqual(_A     ,						_A )



     def  UpperCAmelCase__							(				self							:							Tuple ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Tuple					=		torch.tensor([1, 2, 3] )
       __SCREAMING_SNAKE_CASE      :	str					=		torch.tensor([2, 3, 4] )
       __SCREAMING_SNAKE_CASE      :	List[str]					=		DummyModel()
       __SCREAMING_SNAKE_CASE      :	int					=		torch.optim.Adam(net.parameters() )
       __SCREAMING_SNAKE_CASE      :	int					=		Accelerator()
       with self.assertRaises(_A ) as ve:
         accelerator.register_for_checkpointing(_A     ,						_A     ,						_A     ,						_A )
       __SCREAMING_SNAKE_CASE      :	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  UpperCAmelCase__							(				self							:							str ):







       """simple docstring"""




       with tempfile.TemporaryDirectory() as tmpdir:
         set_seed(42 )
         __SCREAMING_SNAKE_CASE      :	List[str]					=		DummyModel()
         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		torch.optim.Adam(params=model.parameters()     ,						lr=1e-3 )
         __SCREAMING_SNAKE_CASE      :	Tuple					=		torch.optim.lr_scheduler.StepLR(_A     ,						step_size=1     ,						gamma=0.99 )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Tuple					=		dummy_dataloaders()
         __SCREAMING_SNAKE_CASE      :	int					=		ProjectConfiguration(automatic_checkpoint_naming=_A )
         # Train baseline
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		Accelerator(project_dir=_A     ,						project_config=_A )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		accelerator.prepare(
             _A     ,						_A     ,						_A     ,						_A     ,						_A )
         # Save initial
         accelerator.save_state()
         __SCREAMING_SNAKE_CASE      :	Optional[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  UpperCAmelCase__							(				self							:							Dict ):







       """simple docstring"""




       with tempfile.TemporaryDirectory() as tmpdir:
         set_seed(42 )
         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		DummyModel()
         __SCREAMING_SNAKE_CASE      :	List[str]					=		ProjectConfiguration(automatic_checkpoint_naming=_A     ,						total_limit=2 )
         # Train baseline
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		Accelerator(project_dir=_A     ,						project_config=_A )
         __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		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  UpperCAmelCase__							(				self							:							Tuple ):







       """simple docstring"""




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

from PIL import Image  # type: ignore


def       snake_case   (	snake_case      : float					,		snake_case      : float					,		snake_case      : int			) ->  float:


    """simple docstring"""


    lowerCAmelCase 						=							x
    lowerCAmelCase 						=							y
    for step in range(snake_case			):  # noqa: B007
        lowerCAmelCase 						=							a * a - b * b + x
        lowerCAmelCase 						=							2 * a * b + y
        lowerCAmelCase 						=							a_new

        # divergence happens for all complex number with an absolute value
        # greater than 4
        if a * a + b * b > 4:
            break
    return step / (max_step - 1)


def       snake_case   (	snake_case      : float			) ->  tuple:


    """simple docstring"""


    if distance == 1:
        return (0, 0, 0)
    else:
        return (255, 255, 255)


def       snake_case   (	snake_case      : float			) ->  tuple:


    """simple docstring"""


    if distance == 1:
        return (0, 0, 0)
    else:
        return tuple(round(i * 255			) for i in colorsys.hsv_to_rgb(snake_case					,		1					,		1			)			)


def       snake_case   (	snake_case      : int = 800					,		snake_case      : int = 600					,		snake_case      : float = -0.6					,		snake_case      : float = 0					,		snake_case      : float = 3.2					,		snake_case      : int = 50					,		snake_case      : bool = True					,		) ->  Image.Image:


    """simple docstring"""


    lowerCAmelCase 						=							Image.new('RGB'					,		(image_width, image_height)			)
    lowerCAmelCase 						=							img.load()

    # loop through the image-coordinates
    for image_x in range(snake_case			):
        for image_y in range(snake_case			):
            # determine the figure-coordinates based on the image-coordinates
            lowerCAmelCase 						=							figure_width / image_width * image_height
            lowerCAmelCase 						=							figure_center_x + (image_x / image_width - 0.5) * figure_width
            lowerCAmelCase 						=							figure_center_y + (image_y / image_height - 0.5) * figure_height

            lowerCAmelCase 						=							get_distance(snake_case					,		snake_case					,		snake_case			)

            # color the corresponding pixel based on the selected coloring-function
            if use_distance_color_coding:
                lowerCAmelCase 						=							get_color_coded_rgb(snake_case			)
            else:
                lowerCAmelCase 						=							get_black_and_white_rgb(snake_case			)

    return img


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     # colored version, full figure
     _UpperCamelCase						:  Dict							       =				get_image()

     # uncomment for colored version, different section, zoomed in
     # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
     # figure_width = 0.8)

     # uncomment for black and white version, full figure
     # img = get_image(use_distance_color_coding = False)

     # uncomment to save the image
     # img.save("mandelbrot.png")

     img.show()





