
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 unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()


class 	lowerCAmelCase  (   unittest.TestCase ):







       @property
       def       snake_case (				self      :			str   ):







            """simple docstring"""







            torch.manual_seed(0   )
            __lowercase      		=UNetaDModel(
                block_out_channels=(32, 64)    ,   layers_per_block=2    ,   sample_size=32    ,   in_channels=3    ,   out_channels=3    ,   down_block_types=('DownBlock2D', 'AttnDownBlock2D')    ,   up_block_types=('AttnUpBlock2D', 'UpBlock2D')    ,   )
            return model







       def       snake_case (				self      :			int   ):







            """simple docstring"""







            __lowercase      		=self.dummy_uncond_unet
            __lowercase      		=PNDMScheduler()

            __lowercase      		=PNDMPipeline(unet=__lowercase    ,   scheduler=__lowercase   )
            pndm.to(__lowercase   )
            pndm.set_progress_bar_config(disable=__lowercase   )

            __lowercase      		=torch.manual_seed(0   )
            __lowercase      		=pndm(generator=__lowercase    ,   num_inference_steps=20    ,   output_type='numpy'   ).images

            __lowercase      		=torch.manual_seed(0   )
            __lowercase      		=pndm(generator=__lowercase    ,   num_inference_steps=20    ,   output_type='numpy'    ,   return_dict=__lowercase   )[0]

            __lowercase      		=image[0, -3:, -3:, -1]
            __lowercase      		=image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 32, 32, 3)
            __lowercase      		=np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]   )

            assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
            assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1E-2






@slow
@require_torch
class 	lowerCAmelCase  (   unittest.TestCase ):







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







            """simple docstring"""







            __lowercase      		='google/ddpm-cifar10-32'

            __lowercase      		=UNetaDModel.from_pretrained(__lowercase   )
            __lowercase      		=PNDMScheduler()

            __lowercase      		=PNDMPipeline(unet=__lowercase    ,   scheduler=__lowercase   )
            pndm.to(__lowercase   )
            pndm.set_progress_bar_config(disable=__lowercase   )
            __lowercase      		=torch.manual_seed(0   )
            __lowercase      		=pndm(generator=__lowercase    ,   output_type='numpy'   ).images

            __lowercase      		=image[0, -3:, -3:, -1]

            assert image.shape == (1, 32, 32, 3)
            __lowercase      		=np.array([0.1_5_6_4, 0.1_4_6_4_5, 0.1_4_0_6, 0.1_4_7_1_5, 0.1_2_4_2_5, 0.1_4_0_4_5, 0.1_3_1_1_5, 0.1_2_1_7_5, 0.1_2_5]   )

            assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2


