






"""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_	:				List[str]										= logging.getLogger(__name__)



def     __lowercase					(    a :				Tuple=2       ,		a :				Tuple=3       ,		a :				Union[str, Any]=16       ,		a :				int = 10       ,		a :				int = 2 )					->					List[Any]:

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

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



def     __lowercase					(    a :				Optional[int]       ,		a :				Optional[Any]       ,		a :				str       ,		a :				Any       ,		a :				Dict       ,		a :				Optional[int]=None )					->					Optional[int]:
      __snake_case      :    List[Any]  			=[]
      for epoch in range(a ):
            # Train quickly
            model.train()
            for batch in dataloader:
                  __snake_case			,				__snake_case      :    int  			=batch
                  __snake_case      :    int  			=model(a )
                  __snake_case      :    Union[str, 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      _lowercase (     nn.Module						):


      def __init__(    self				:	Tuple						):





            """simple docstring"""







            super().__init__()
            __snake_case      :    Optional[Any]  			=nn.Parameter(torch.randn(1						)						)
            __snake_case      :    Tuple  			=nn.Parameter(torch.randn(1						)						)







      def _UpperCamelCase						(    self				:	Any							,   a				:	List[Any]						):





            """simple docstring"""







            return x * self.a + self.b



class      _lowercase (     unittest.TestCase						):


      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(4_2						)
                  __snake_case      :    Dict  			=DummyModel()
                  __snake_case      :    List[Any]  			=torch.optim.Adam(params=model.parameters()							,   lr=1e-3						)
                  __snake_case			,				__snake_case      :    Any  			=dummy_dataloaders()
                  __snake_case      :    Union[str, Any]  			=ProjectConfiguration(total_limit=1							,   project_dir=a							,   automatic_checkpoint_naming=a						)
                  # Train baseline
                  __snake_case      :    Optional[Any]  			=Accelerator(project_config=a						)
                  __snake_case			,				__snake_case			,				__snake_case			,				__snake_case      :    Optional[int]  			=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				:	Optional[Any]						):





            """simple docstring"""







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

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

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


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(4_2						)
                  __snake_case      :    List[str]  			=DummyModel()
                  __snake_case      :    Union[str, Any]  			=torch.optim.Adam(params=model.parameters()							,   lr=1e-3						)
                  __snake_case			,				__snake_case      :    Optional[Any]  			=dummy_dataloaders()
                  __snake_case      :    List[str]  			=ProjectConfiguration(automatic_checkpoint_naming=a						)

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

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

                  __snake_case      :    Tuple  			=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						)
                  ((__snake_case)			,				(__snake_case))      :    Dict  			=model.a.item(), model.b.item()
                  __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				:	Any						):





            """simple docstring"""







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





            """simple docstring"""







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





            """simple docstring"""







            with tempfile.TemporaryDirectory() as tmpdir:
                  set_seed(4_2						)
                  __snake_case      :    Tuple  			=DummyModel()
                  __snake_case      :    List[Any]  			=ProjectConfiguration(automatic_checkpoint_naming=a							,   total_limit=2						)
                  # Train baseline
                  __snake_case      :    Any  			=Accelerator(project_dir=a							,   project_config=a						)
                  __snake_case      :    str  			=accelerator.prepare(a						)
                  # Save 3 states:
                  for _ in range(1_1						):
                        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				:	Any						):





            """simple docstring"""







            __snake_case      :    Dict  			=['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__						)]
            execute_subprocess_async(a							,   env=os.environ.copy()						)


if __name__ == "__main__":
    UpperCamelCase_	:				Dict										= """/tmp/accelerate/state_checkpointing"""
    UpperCamelCase_	:				Union[str, Any]										= DummyModel()
    UpperCamelCase_	:				Optional[Any]										= torch.optim.Adam(params=model.parameters(), lr=1e-3)
    UpperCamelCase_	:				Optional[Any]										= torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
    UpperCamelCase_							,							UpperCamelCase_	:				int										= dummy_dataloaders()
    UpperCamelCase_	:				Union[str, Any]										= ProjectConfiguration(automatic_checkpoint_naming=True)
    # Train baseline
    UpperCamelCase_	:				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[str]										= accelerator.prepare(
        model, optimizer, train_dataloader, valid_dataloader, scheduler
    )
    UpperCamelCase_							,							UpperCamelCase_	:				Any										= 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_	:				int										= group["""params"""][0].device
        break
    assert param_device.type == accelerator.device.type
    UpperCamelCase_	:				Union[str, Any]										= 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_	:				Tuple										= 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_	:				List[Any]										= 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_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCamelCase_	:				Any										= {"""configuration_reformer""": ["""REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ReformerConfig"""]}

try:
    if not is_sentencepiece_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_	:				List[str]										= ["""ReformerTokenizer"""]

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_	:				List[str]										= ["""ReformerTokenizerFast"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase_	:				Optional[int]										= [
        """REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """ReformerAttention""",
        """ReformerForMaskedLM""",
        """ReformerForQuestionAnswering""",
        """ReformerForSequenceClassification""",
        """ReformerLayer""",
        """ReformerModel""",
        """ReformerModelWithLMHead""",
        """ReformerPreTrainedModel""",
    ]


if TYPE_CHECKING:
    from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig

    try:
        if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_reformer import ReformerTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_reformer_fast import ReformerTokenizerFast

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_reformer import (
            REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
            ReformerAttention,
            ReformerForMaskedLM,
            ReformerForQuestionAnswering,
            ReformerForSequenceClassification,
            ReformerLayer,
            ReformerModel,
            ReformerModelWithLMHead,
            ReformerPreTrainedModel,
        )

else:
    import sys

    UpperCamelCase_	:				Tuple										= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


