



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


lowercase__			   =  logging.getLogger(__name__)





def       __magic_name__    (   _lowerCamelCase				: Tuple=2  ,       _lowerCamelCase				: Union[str, Any]=3  ,       _lowerCamelCase				: Optional[int]=1_6  ,       _lowerCamelCase				: int = 1_0  ,       _lowerCamelCase				: int = 2					):

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

       __a		:		List[str]									=       get_dataset(_lowerCamelCase					)
       __a		:		int									=       get_dataset(_lowerCamelCase					)
       __a		:		Tuple									=       DataLoader(_lowerCamelCase  ,       shuffle=_lowerCamelCase  ,       batch_size=_lowerCamelCase  ,       num_workers=4					)
       __a		:		str									=       DataLoader(_lowerCamelCase  ,       shuffle=_lowerCamelCase  ,       batch_size=_lowerCamelCase  ,       num_workers=4					)
       return (train_dataloader, valid_dataloader)





def       __magic_name__    (   _lowerCamelCase				: Tuple  ,       _lowerCamelCase				: Optional[int]  ,       _lowerCamelCase				: str  ,       _lowerCamelCase				: Tuple  ,       _lowerCamelCase				: Union[str, Any]  ,       _lowerCamelCase				: Optional[Any]=None					):
       __a		:		Dict									=       []
       for epoch in range(_lowerCamelCase					):
              # Train quickly
              model.train()
              for batch in dataloader:
                     __a		:		Tuple									=       batch
                     __a		:		Union[str, Any]									=       model(_lowerCamelCase					)
                     __a		:		int									=       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 SCREAMING_SNAKE_CASE__					(		nn.Module      ):



      def __init__(self							):





             '''simple docstring'''

             super().__init__()
             __a		:		int									=       nn.Parameter(torch.randn(1							)							)
             __a		:		Any									=       nn.Parameter(torch.randn(1							)							)





      def     lowerCAmelCase__(self						,     _lowercase							):





             '''simple docstring'''

             return x * self.a + self.b







class SCREAMING_SNAKE_CASE__					(		unittest.TestCase      ):



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             with tempfile.TemporaryDirectory() as tmpdir:
                    set_seed(42							)
                    __a		:		Optional[int]									=       DummyModel()
                    __a		:		List[str]									=       torch.optim.Adam(params=model.parameters()						,     lr=1e-3							)
                    __a		:		Optional[int]									=       dummy_dataloaders()
                    __a		:		List[str]									=       ProjectConfiguration(total_limit=1						,     project_dir=_lowercase						,     automatic_checkpoint_naming=_lowercase							)
                    # Train baseline
                    __a		:		str									=       Accelerator(project_config=_lowercase							)
                    __a		:		Optional[int]									=       accelerator.prepare(
                        _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    # Save initial
                    accelerator.save_state()

                    # Save second state
                    accelerator.save_state()
                    self.assertEqual(len(os.listdir(accelerator.project_dir							)							)						,     1							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

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

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

                    __a		:		Optional[Any]									=       train(2						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    # Save everything
                    __a		:		Optional[Any]									=       os.path.join(_lowercase						,     """checkpoint"""							)
                    accelerator.save_state(_lowercase							)

                    # Load everything back in and make sure all states work
                    accelerator.load_state(_lowercase							)
                    test_rands += train(1						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    (__a)		:		str									=       model.a.item(), model.b.item()
                    __a		:		int									=       optimizer.state_dict()
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)



      def     lowerCAmelCase__(self							):





             '''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		:		List[str]									=       dummy_dataloaders()
                    __a		:		Optional[Any]									=       ProjectConfiguration(automatic_checkpoint_naming=_lowercase							)

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

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

                    __a		:		Dict									=       train(2						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    # Save everything
                    accelerator.save_state()

                    # Load everything back in and make sure all states work
                    accelerator.load_state(os.path.join(_lowercase						,     """checkpoints"""						,     """checkpoint_1"""							)							)
                    test_rands += train(1						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    (__a)		:		int									=       model.a.item(), model.b.item()
                    __a		:		str									=       optimizer.state_dict()
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)
                    self.assertEqual(_lowercase						,     _lowercase							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

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





             '''simple docstring'''

             with tempfile.TemporaryDirectory() as tmpdir:
                    set_seed(42							)
                    __a		:		int									=       DummyModel()
                    __a		:		int									=       torch.optim.Adam(params=model.parameters()						,     lr=1e-3							)
                    __a		:		Tuple									=       torch.optim.lr_scheduler.StepLR(_lowercase						,     step_size=1						,     gamma=0.99							)
                    __a		:		Optional[Any]									=       dummy_dataloaders()
                    __a		:		Optional[int]									=       ProjectConfiguration(automatic_checkpoint_naming=_lowercase							)
                    # Train baseline
                    __a		:		List[Any]									=       Accelerator(project_dir=_lowercase						,     project_config=_lowercase							)
                    __a		:		Union[str, Any]									=       accelerator.prepare(
                        _lowercase						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    # Save initial
                    accelerator.save_state()
                    __a		:		Optional[int]									=       scheduler.state_dict()
                    train(3						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase						,     _lowercase							)
                    self.assertNotEqual(_lowercase						,     scheduler.state_dict()							)

                    # Load everything back in and make sure all states work
                    accelerator.load_state(os.path.join(_lowercase						,     """checkpoints"""						,     """checkpoint_0"""							)							)
                    self.assertEqual(_lowercase						,     scheduler.state_dict()							)



      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             with tempfile.TemporaryDirectory() as tmpdir:
                    set_seed(42							)
                    __a		:		Dict									=       DummyModel()
                    __a		:		Dict									=       ProjectConfiguration(automatic_checkpoint_naming=_lowercase						,     total_limit=2							)
                    # Train baseline
                    __a		:		Tuple									=       Accelerator(project_dir=_lowercase						,     project_config=_lowercase							)
                    __a		:		str									=       accelerator.prepare(_lowercase							)
                    # Save 3 states:
                    for _ in range(11							):
                           accelerator.save_state()
                    self.assertTrue(not os.path.exists(os.path.join(_lowercase						,     """checkpoints"""						,     """checkpoint_0"""							)							)							)
                    self.assertTrue(os.path.exists(os.path.join(_lowercase						,     """checkpoints"""						,     """checkpoint_9"""							)							)							)
                    self.assertTrue(os.path.exists(os.path.join(_lowercase						,     """checkpoints"""						,     """checkpoint_10"""							)							)							)





      @require_cuda
      def     lowerCAmelCase__(self							):





             '''simple docstring'''

             __a		:		List[Any]									=       ["""torchrun""", F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__							)]
             execute_subprocess_async(_lowercase						,     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"""

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available


lowercase__			   =  {
    "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	lowercase__			   =  [
	    "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
	    "ErnieForCausalLM",
	    "ErnieForMaskedLM",
	    "ErnieForMultipleChoice",
	    "ErnieForNextSentencePrediction",
	    "ErnieForPreTraining",
	    "ErnieForQuestionAnswering",
	    "ErnieForSequenceClassification",
	    "ErnieForTokenClassification",
	    "ErnieModel",
	    "ErniePreTrainedModel",
	]

if TYPE_CHECKING:
	from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_ernie import (
		    ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
		    ErnieForCausalLM,
		    ErnieForMaskedLM,
		    ErnieForMultipleChoice,
		    ErnieForNextSentencePrediction,
		    ErnieForPreTraining,
		    ErnieForQuestionAnswering,
		    ErnieForSequenceClassification,
		    ErnieForTokenClassification,
		    ErnieModel,
		    ErniePreTrainedModel,
		)

else:
	import sys

	lowercase__			   =  _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)

