
'''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         =    logging.getLogger(__name__)





def 					UpperCAmelCase_		(__a      :    Optional[int]=2 ,	__a      :    Optional[int]=3 ,	__a      :    int=1_6 ,	__a      :    int = 1_0 ,	__a      :    int = 2 ):






   """simple docstring"""

   def get_dataset(__a      :    Any ):
      _a				:	Any			=   torch.randn(batch_size * n_batches ,	1 )
      return TensorDataset(__a ,	a * x + b + 0.1 * torch.randn(batch_size * n_batches ,	1 ) )

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





def 					UpperCAmelCase_		(__a      :    List[str] ,	__a      :    int ,	__a      :    str ,	__a      :    Union[str, Any] ,	__a      :    Any ,	__a      :    Optional[Any]=None ):






   """simple docstring"""

   _a				:	Dict			=   []
   for epoch in range(__a ):
      # Train quickly
      model.train()
      for batch in dataloader:
         _a,  _a				:	int			=   batch
         _a				:	Any			=   model(__a )
         _a				:	List[Any]			=   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 UpperCAmelCase__	( nn.Module	):





  """simple docstring"""

  def __init__(		self      :     List[Any]       ):


     '''simple docstring'''






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


  def   __lowercase		(		self      :     Optional[Any]							,_a      :     Tuple       ):


     '''simple docstring'''






     return x * self.a + self.b







class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






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


     '''simple docstring'''






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

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

        _a				:	List[Any]			=   train(2							,_a							,_a							,_a							,_a       )
        # Save everything
        _a				:	Tuple			=   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       )
        ((_a),  (_a))				:	Dict			=   model.a.item(), model.b.item()
        _a				:	Union[str, Any]			=   optimizer.state_dict()
        self.assertEqual(_a							,_a       )
        self.assertEqual(_a							,_a       )
        self.assertEqual(_a							,_a       )
        self.assertEqual(_a							,_a       )


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(42       )
        _a				:	Tuple			=   DummyModel()
        _a				:	List[Any]			=   torch.optim.Adam(params=model.parameters()							,lr=1E-3       )
        _a,  _a				:	Optional[Any]			=   dummy_dataloaders()
        _a				:	Optional[int]			=   ProjectConfiguration(automatic_checkpoint_naming=_a       )

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

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

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


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


     '''simple docstring'''






     _a				:	Dict			=   torch.tensor([1, 2, 3]       )
     _a				:	Union[str, Any]			=   torch.tensor([2, 3, 4]       )
     _a				:	Optional[Any]			=   DummyModel()
     _a				:	int			=   torch.optim.Adam(net.parameters()       )
     _a				:	Dict			=   Accelerator()
     with self.assertRaises(_a       ) as ve:
        accelerator.register_for_checkpointing(_a							,_a							,_a							,_a       )
     _a				:	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   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






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


     '''simple docstring'''






     with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(42       )
        _a				:	Any			=   DummyModel()
        _a				:	List[Any]			=   ProjectConfiguration(automatic_checkpoint_naming=_a							,total_limit=2       )
        # Train baseline
        _a				:	Dict			=   Accelerator(project_dir=_a							,project_config=_a       )
        _a				:	List[str]			=   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   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






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

from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home


__lowerCAmelCase         =    HUGGINGFACE_HUB_CACHE


__lowerCAmelCase         =    """config.json"""
__lowerCAmelCase         =    """diffusion_pytorch_model.bin"""
__lowerCAmelCase         =    """diffusion_flax_model.msgpack"""
__lowerCAmelCase         =    """model.onnx"""
__lowerCAmelCase         =    """diffusion_pytorch_model.safetensors"""
__lowerCAmelCase         =    """weights.pb"""
__lowerCAmelCase         =    """https://huggingface.co"""
__lowerCAmelCase         =    default_cache_path
__lowerCAmelCase         =    """diffusers_modules"""
__lowerCAmelCase         =    os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules"""))
__lowerCAmelCase         =    ["""fp16""", """non-ema"""]
__lowerCAmelCase         =    """.self_attn"""



