


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


__UpperCAmelCase    :Dict				       =     logging.getLogger(__name__)




def 			_a			(		_lowercase      :			Tuple=2    ,      _lowercase      :			Optional[int]=3    ,      _lowercase      :			Tuple=16    ,      _lowercase      :			int = 10    ,      _lowercase      :			int = 2						):





     '''simple docstring'''






     def get_dataset(_lowercase      :			List[str]						):
          __UpperCAmelCase			:				int													=    torch.randn(batch_size * n_batches    ,      1						)
          return TensorDataset(a_    ,      a * x + b + 0.1 * torch.randn(batch_size * n_batches    ,      1						)						)

     __UpperCAmelCase			:				List[Any]													=    get_dataset(a_						)
     __UpperCAmelCase			:				Dict													=    get_dataset(a_						)
     __UpperCAmelCase			:				Optional[Any]													=    DataLoader(a_    ,      shuffle=a_    ,      batch_size=a_    ,      num_workers=4						)
     __UpperCAmelCase			:				int													=    DataLoader(a_    ,      shuffle=a_    ,      batch_size=a_    ,      num_workers=4						)
     return (train_dataloader, valid_dataloader)




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





     '''simple docstring'''






     __UpperCAmelCase			:				int													=    []
     for epoch in range(a_						):
          # Train quickly
          model.train()
          for batch in dataloader:
               __UpperCAmelCase			:				List[Any]													=    batch
               __UpperCAmelCase			:				List[Any]													=    model(a_						)
               __UpperCAmelCase			:				Dict													=    torch.nn.functional.mse_loss(a_    ,      a_						)
               accelerator.backward(a_						)
               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 ):


     """simple docstring"""






     def __init__(       self  :	Optional[int]    )		->							Optional[Any]:
          super().__init__()
          __UpperCAmelCase			:				Optional[int]													=    nn.Parameter(torch.randn(1    )    )
          __UpperCAmelCase			:				List[Any]													=    nn.Parameter(torch.randn(1    )    )






     def 				lowerCamelCase__				(       self  :	Optional[Any]							,				snake_case  :	List[str]    )		->							Optional[int]:
          return x * self.a + self.b



class 			a       (	unittest.TestCase ):


     """simple docstring"""






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

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

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

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

               # Train partially
               set_seed(42    )
               __UpperCAmelCase			:				Dict													=    DummyModel()
               __UpperCAmelCase			:				Union[str, Any]													=    torch.optim.Adam(params=model.parameters()							,				lr=1E-3    )
               __UpperCAmelCase			:				Optional[Any]													=    dummy_dataloaders()
               __UpperCAmelCase			:				Tuple													=    ProjectConfiguration(iteration=1							,				automatic_checkpoint_naming=__snake_case    )
               __UpperCAmelCase			:				List[str]													=    Accelerator(project_dir=__snake_case							,				project_config=__snake_case    )
               __UpperCAmelCase			:				Tuple													=    accelerator.prepare(
                   __snake_case							,				__snake_case							,				__snake_case							,				__snake_case    )
               accelerator.load_state(os.path.join(__snake_case							,				'''checkpoints'''							,				'''checkpoint_0'''    )    )
               (__UpperCAmelCase)			:				int													=    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			:				List[str]													=    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)			:				Any													=    model.a.item(), model.b.item()
               __UpperCAmelCase			:				int													=    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  :	Dict    )		->							Dict:
          __UpperCAmelCase			:				str													=    torch.tensor([1, 2, 3]    )
          __UpperCAmelCase			:				int													=    torch.tensor([2, 3, 4]    )
          __UpperCAmelCase			:				Union[str, Any]													=    DummyModel()
          __UpperCAmelCase			:				Any													=    torch.optim.Adam(net.parameters()    )
          __UpperCAmelCase			:				Union[str, Any]													=    Accelerator()
          with self.assertRaises(__snake_case    ) as ve:
               accelerator.register_for_checkpointing(__snake_case							,				__snake_case							,				__snake_case							,				__snake_case    )
          __UpperCAmelCase			:				Union[str, Any]													=    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  :	Any    )		->							Optional[Any]:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42    )
               __UpperCAmelCase			:				List[str]													=    DummyModel()
               __UpperCAmelCase			:				Optional[Any]													=    torch.optim.Adam(params=model.parameters()							,				lr=1E-3    )
               __UpperCAmelCase			:				Optional[int]													=    torch.optim.lr_scheduler.StepLR(__snake_case							,				step_size=1							,				gamma=0.99    )
               __UpperCAmelCase			:				List[Any]													=    dummy_dataloaders()
               __UpperCAmelCase			:				Tuple													=    ProjectConfiguration(automatic_checkpoint_naming=__snake_case    )
               # Train baseline
               __UpperCAmelCase			:				List[Any]													=    Accelerator(project_dir=__snake_case							,				project_config=__snake_case    )
               __UpperCAmelCase			:				str													=    accelerator.prepare(
                   __snake_case							,				__snake_case							,				__snake_case							,				__snake_case							,				__snake_case    )
               # Save initial
               accelerator.save_state()
               __UpperCAmelCase			:				Optional[Any]													=    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  :	Any    )		->							int:
          with tempfile.TemporaryDirectory() as tmpdir:
               set_seed(42    )
               __UpperCAmelCase			:				int													=    DummyModel()
               __UpperCAmelCase			:				Optional[Any]													=    ProjectConfiguration(automatic_checkpoint_naming=__snake_case							,				total_limit=2    )
               # Train baseline
               __UpperCAmelCase			:				Dict													=    Accelerator(project_dir=__snake_case							,				project_config=__snake_case    )
               __UpperCAmelCase			:				Tuple													=    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  :	str    )		->							List[str]:
          __UpperCAmelCase			:				List[str]													=    ['''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    :List[str]				       =     "/tmp/accelerate/state_checkpointing"
      __UpperCAmelCase    :Dict				       =     DummyModel()
      __UpperCAmelCase    :List[Any]				       =     torch.optim.Adam(params=model.parameters(), lr=1e-3)
      __UpperCAmelCase    :str				       =     torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
      __UpperCAmelCase       ,					__UpperCAmelCase    :List[str]				       =     dummy_dataloaders()
      __UpperCAmelCase    :int				       =     ProjectConfiguration(automatic_checkpoint_naming=True)
      # Train baseline
      __UpperCAmelCase    :Optional[int]				       =     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       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase    :List[Any]				       =     accelerator.prepare(
          model, optimizer, train_dataloader, valid_dataloader, scheduler
      )
      __UpperCAmelCase       ,					__UpperCAmelCase    :Dict				       =     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    :Optional[Any]				       =     group["params"][0].device
            break
      assert param_device.type == accelerator.device.type
      __UpperCAmelCase    :Optional[int]				       =     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    :Optional[Any]				       =     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    :str				       =     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 numpy as np
from cva import destroyAllWindows, imread, imshow, waitKey



class 			a       :


     """simple docstring"""






     def __init__(       self  :	Union[str, Any]							,				snake_case  :	List[Any]							,				snake_case  :	int							,				snake_case  :	int    )		->							List[Any]:
          if dst_width < 0 or dst_height < 0:
               raise ValueError('''Destination width/height should be > 0'''    )

          __UpperCAmelCase			:				str													=    img
          __UpperCAmelCase			:				List[Any]													=    img.shape[1]
          __UpperCAmelCase			:				Optional[Any]													=    img.shape[0]
          __UpperCAmelCase			:				Dict													=    dst_width
          __UpperCAmelCase			:				List[str]													=    dst_height

          __UpperCAmelCase			:				Union[str, Any]													=    self.src_w / self.dst_w
          __UpperCAmelCase			:				List[str]													=    self.src_h / self.dst_h

          __UpperCAmelCase			:				Optional[int]													=    (
              np.ones((self.dst_h, self.dst_w, 3)							,				np.uinta    ) * 255
          )

     def 				lowerCamelCase__				(       self  :	Any    )		->							str:
          for i in range(self.dst_h    ):
               for j in range(self.dst_w    ):
                    __UpperCAmelCase			:				Any													=    self.img[self.get_y(snake_case    )][self.get_x(snake_case    )]

     def 				lowerCamelCase__				(       self  :	int							,				snake_case  :	int    )		->							int:
          return int(self.ratio_x * x    )






     def 				lowerCamelCase__				(       self  :	Optional[Any]							,				snake_case  :	int    )		->							int:
          return int(self.ratio_y * y    )


if __name__ == "__main__":
      __UpperCAmelCase       ,					__UpperCAmelCase    :int				       =     8_0_0, 6_0_0
      __UpperCAmelCase    :Dict				       =     imread("image_data/lena.jpg", 1)
      __UpperCAmelCase    :int				       =     NearestNeighbour(im, dst_w, dst_h)
      n.process()

      imshow(
          f"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output
      )
      waitKey(0)
      destroyAllWindows()