





"""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     :						Any						       =  logging.getLogger(__name__)

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    Any=2  ,     _UpperCAmelCase					:    Optional[Any]=3  ,     _UpperCAmelCase					:    Any=16  ,     _UpperCAmelCase					:    int = 10  ,     _UpperCAmelCase					:    int = 2			):

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

 lowerCAmelCase    				= get_dataset(_UpperCAmelCase			)
 lowerCAmelCase    				= get_dataset(_UpperCAmelCase			)
 lowerCAmelCase    				= DataLoader(_UpperCAmelCase  ,     shuffle=_UpperCAmelCase  ,     batch_size=_UpperCAmelCase  ,     num_workers=4			)
 lowerCAmelCase    				= DataLoader(_UpperCAmelCase  ,     shuffle=_UpperCAmelCase  ,     batch_size=_UpperCAmelCase  ,     num_workers=4			)
 return (train_dataloader, valid_dataloader)

def 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    str  ,     _UpperCAmelCase					:    Union[str, Any]  ,     _UpperCAmelCase					:    Tuple  ,     _UpperCAmelCase					:    str  ,     _UpperCAmelCase					:    List[str]  ,     _UpperCAmelCase					:    int=None			):
 lowerCAmelCase    				= []
 for epoch in range(_UpperCAmelCase			):
  # Train quickly
  model.train()
  for batch in dataloader:
   lowerCAmelCase				,lowerCAmelCase    				= batch
   lowerCAmelCase    				= model(_UpperCAmelCase			)
   lowerCAmelCase    				= torch.nn.functional.mse_loss(_UpperCAmelCase  ,     _UpperCAmelCase			)
   accelerator.backward(_UpperCAmelCase			)
   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  ):



 def __init__(     self     ):







  """simple docstring"""






  super().__init__()
  lowerCAmelCase    				= nn.Parameter(torch.randn(1     )     )
  lowerCAmelCase    				= nn.Parameter(torch.randn(1     )     )



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






  return x * self.a + self.b







class       a							(   unittest.TestCase  ):



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  with tempfile.TemporaryDirectory() as tmpdir:
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= torch.optim.Adam(params=model.parameters()				,       lr=1E-3     )
   lowerCAmelCase				,lowerCAmelCase    				= dummy_dataloaders()
   lowerCAmelCase    				= ProjectConfiguration(total_limit=1				,       project_dir=_snake_case				,       automatic_checkpoint_naming=_snake_case     )
   # Train baseline
   lowerCAmelCase    				= Accelerator(project_config=_snake_case     )
   lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= 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    UpperCamelCase__  (     self     ):







  """simple docstring"""






  with tempfile.TemporaryDirectory() as tmpdir:
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= torch.optim.Adam(params=model.parameters()				,       lr=1E-3     )
   lowerCAmelCase				,lowerCAmelCase    				= dummy_dataloaders()
   # Train baseline
   lowerCAmelCase    				= Accelerator()
   lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= accelerator.prepare(
       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   # Save initial
   lowerCAmelCase    				= os.path.join(_snake_case				,       'initial'     )
   accelerator.save_state(_snake_case     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()
   lowerCAmelCase    				= train(3				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()

   # Train partially
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= torch.optim.Adam(params=model.parameters()				,       lr=1E-3     )
   lowerCAmelCase				,lowerCAmelCase    				= dummy_dataloaders()
   lowerCAmelCase    				= Accelerator()
   lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= accelerator.prepare(
       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   accelerator.load_state(_snake_case     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()
   self.assertEqual(_snake_case				,       _snake_case     )
   self.assertEqual(_snake_case				,       _snake_case     )
   self.assertEqual(_snake_case				,       _snake_case     )

   lowerCAmelCase    				= train(2				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   # Save everything
   lowerCAmelCase    				= 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     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= 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    UpperCamelCase__  (     self     ):







  """simple docstring"""






  with tempfile.TemporaryDirectory() as tmpdir:
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= torch.optim.Adam(params=model.parameters()				,       lr=1E-3     )
   lowerCAmelCase				,lowerCAmelCase    				= dummy_dataloaders()
   lowerCAmelCase    				= ProjectConfiguration(automatic_checkpoint_naming=_snake_case     )

   # Train baseline
   lowerCAmelCase    				= Accelerator(project_dir=_snake_case				,       project_config=_snake_case     )
   lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= accelerator.prepare(
       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   # Save initial
   accelerator.save_state()
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()
   lowerCAmelCase    				= train(3				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()

   # Train partially
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= torch.optim.Adam(params=model.parameters()				,       lr=1E-3     )
   lowerCAmelCase				,lowerCAmelCase    				= dummy_dataloaders()
   lowerCAmelCase    				= ProjectConfiguration(iteration=1				,       automatic_checkpoint_naming=_snake_case     )
   lowerCAmelCase    				= Accelerator(project_dir=_snake_case				,       project_config=_snake_case     )
   lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase				,lowerCAmelCase    				= accelerator.prepare(
       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     )
   accelerator.load_state(os.path.join(_snake_case				,       'checkpoints'				,       'checkpoint_0'     )     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= optimizer.state_dict()
   self.assertEqual(_snake_case				,       _snake_case     )
   self.assertEqual(_snake_case				,       _snake_case     )
   self.assertEqual(_snake_case				,       _snake_case     )

   lowerCAmelCase    				= 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     )
   ((lowerCAmelCase)				,(lowerCAmelCase))    				= model.a.item(), model.b.item()
   lowerCAmelCase    				= 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    UpperCamelCase__  (     self     ):







  """simple docstring"""






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







  """simple docstring"""






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







  """simple docstring"""






  with tempfile.TemporaryDirectory() as tmpdir:
   set_seed(42     )
   lowerCAmelCase    				= DummyModel()
   lowerCAmelCase    				= ProjectConfiguration(automatic_checkpoint_naming=_snake_case				,       total_limit=2     )
   # Train baseline
   lowerCAmelCase    				= Accelerator(project_dir=_snake_case				,       project_config=_snake_case     )
   lowerCAmelCase    				= 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    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= ['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     :						Any						       =  '''/tmp/accelerate/state_checkpointing'''
       __UpperCamelCase     :						int						       =  DummyModel()
       __UpperCamelCase     :						List[str]						       =  torch.optim.Adam(params=model.parameters(), lr=1e-3)
       __UpperCamelCase     :						Optional[int]						       =  torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
       __UpperCamelCase       ,__UpperCamelCase     :						Dict						       =  dummy_dataloaders()
       __UpperCamelCase     :						List[str]						       =  ProjectConfiguration(automatic_checkpoint_naming=True)
       # Train baseline
       __UpperCamelCase     :						Tuple						       =  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     :						Union[str, Any]						       =  accelerator.prepare(
           model, optimizer, train_dataloader, valid_dataloader, scheduler
       )
       __UpperCamelCase       ,__UpperCamelCase     :						List[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     :						str						       =  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     :						Dict						       =  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"""
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


__UpperCamelCase     :						Dict						       =  {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']}

try:
       if not is_sentencepiece_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase     :						int						       =  ['''LayoutXLMTokenizer''']

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase     :						Any						       =  ['''LayoutXLMTokenizerFast''']

if TYPE_CHECKING:
       from .processing_layoutxlm import LayoutXLMProcessor

       try:
              if not is_sentencepiece_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_layoutxlm import LayoutXLMTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast

else:
       import sys

       __UpperCamelCase     :						Dict						       =  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





