






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


SCREAMING_SNAKE_CASE						=	logging.getLogger(__name__)


def 							lowercase_				(    __A :       int=2					,      __A :       Optional[Any]=3					,      __A :       Optional[Any]=1_6					,      __A :       int = 1_0					,      __A :       int = 2			)       ->      Optional[Any]:



 """simple docstring"""




 def get_dataset(__A :       Tuple			):
  lowercase					:   Optional[Any]				  =torch.randn(batch_size * n_batches					,      1			)
  return TensorDataset(UpperCAmelCase__					,      a * x + b + 0.1 * torch.randn(batch_size * n_batches					,      1			)			)

 lowercase					:   Any				  =get_dataset(UpperCAmelCase__			)
 lowercase					:   str				  =get_dataset(UpperCAmelCase__			)
 lowercase					:   Union[str, Any]				  =DataLoader(UpperCAmelCase__					,      shuffle=UpperCAmelCase__					,      batch_size=UpperCAmelCase__					,      num_workers=4			)
 lowercase					:   Optional[Any]				  =DataLoader(UpperCAmelCase__					,      shuffle=UpperCAmelCase__					,      batch_size=UpperCAmelCase__					,      num_workers=4			)
 return (train_dataloader, valid_dataloader)


def 							lowercase_				(    __A :       str					,      __A :       Optional[int]					,      __A :       Union[str, Any]					,      __A :       Union[str, Any]					,      __A :       List[str]					,      __A :       List[str]=None			)       ->      Dict:



 """simple docstring"""




 lowercase					:   Optional[int]				  =[]
 for epoch in range(UpperCAmelCase__			):
  # Train quickly
  model.train()
  for batch in dataloader:
   lowercase					:   int				  =batch
   lowercase					:   Tuple				  =model(UpperCAmelCase__			)
   lowercase					:   Optional[Any]				  =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 					UpperCAmelCase_					(    nn.Module				):




      """simple docstring"""




      def __init__( self			:		Optional[Any]		)  ->  Union[str, Any]:


       '''simple docstring'''

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






      def 				A__      ( self			:		Optional[int]     ,      UpperCAmelCase			:		Dict		)  ->  List[Any]:


       '''simple docstring'''

       return x * self.a + self.b





class 					UpperCAmelCase_					(    unittest.TestCase				):




      """simple docstring"""




      def 				A__      ( self			:		Dict		)  ->  Tuple:


       '''simple docstring'''

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


       '''simple docstring'''

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

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

        lowercase					:   Optional[int]				  =train(2     ,      lowercase_     ,      lowercase_     ,      lowercase_     ,      lowercase_		)
        # Save everything
        lowercase					:   str				  =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_		)
        (lowercase)					:   Tuple				  =model.a.item(), model.b.item()
        lowercase					:   Tuple				  =optimizer.state_dict()
        self.assertEqual(lowercase_     ,      lowercase_		)
        self.assertEqual(lowercase_     ,      lowercase_		)
        self.assertEqual(lowercase_     ,      lowercase_		)
        self.assertEqual(lowercase_     ,      lowercase_		)






      def 				A__      ( self			:		int		)  ->  List[str]:


       '''simple docstring'''

       with tempfile.TemporaryDirectory() as tmpdir:
        set_seed(42		)
        lowercase					:   Any				  =DummyModel()
        lowercase					:   int				  =torch.optim.Adam(params=model.parameters()     ,      lr=1e-3		)
        lowercase					:   Dict				  =dummy_dataloaders()
        lowercase					:   Tuple				  =ProjectConfiguration(automatic_checkpoint_naming=lowercase_		)

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

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

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






      def 				A__      ( self			:		Any		)  ->  int:


       '''simple docstring'''

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


       '''simple docstring'''

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


       '''simple docstring'''

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


       '''simple docstring'''

       lowercase					:   List[str]				  =["""torchrun""", f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__		)]
       execute_subprocess_async(lowercase_     ,      env=os.environ.copy()		)


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE						=	"/tmp/accelerate/state_checkpointing"
      SCREAMING_SNAKE_CASE						=	DummyModel()
      SCREAMING_SNAKE_CASE						=	torch.optim.Adam(params=model.parameters(), lr=1E-3)
      SCREAMING_SNAKE_CASE						=	torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
      SCREAMING_SNAKE_CASE						=	dummy_dataloaders()
      SCREAMING_SNAKE_CASE						=	ProjectConfiguration(automatic_checkpoint_naming=True)
      # Train baseline
      SCREAMING_SNAKE_CASE						=	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)
      SCREAMING_SNAKE_CASE						=	accelerator.prepare(
          model, optimizer, train_dataloader, valid_dataloader, scheduler
      )
      SCREAMING_SNAKE_CASE						=	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:
            SCREAMING_SNAKE_CASE						=	group["params"][0].device
            break
      assert param_device.type == accelerator.device.type
      SCREAMING_SNAKE_CASE						=	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:
            SCREAMING_SNAKE_CASE						=	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:
            SCREAMING_SNAKE_CASE						=	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 warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class UpperCAmelCase_					(    __A				):




      """simple docstring"""




      UpperCamelCase_								=			['''image_processor''', '''tokenizer''']
      UpperCamelCase_								=			'''LayoutLMv2ImageProcessor'''
      UpperCamelCase_								=			('''LayoutXLMTokenizer''', '''LayoutXLMTokenizerFast''')






      def __init__( self			:		List[str]     ,      UpperCAmelCase			:		Tuple=None     ,      UpperCAmelCase			:		str=None     ,      **UpperCAmelCase			:		Dict		)  ->  Optional[int]:


       '''simple docstring'''

       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''     ,      UpperCAmelCase     ,      )
        lowercase					:   Any				  =kwargs.pop('''feature_extractor'''		)

       lowercase					:   Dict				  =image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
        raise ValueError('''You need to specify an `image_processor`.'''		)
       if tokenizer is None:
        raise ValueError('''You need to specify a `tokenizer`.'''		)

       super().__init__(UpperCAmelCase     ,      UpperCAmelCase		)






      def __call__( self			:		Any     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None     ,      UpperCAmelCase			:		Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None     ,      UpperCAmelCase			:		Union[List[List[int]], List[List[List[int]]]] = None     ,      UpperCAmelCase			:		Optional[Union[List[int], List[List[int]]]] = None     ,      UpperCAmelCase			:		bool = True     ,      UpperCAmelCase			:		Union[bool, str, PaddingStrategy] = False     ,      UpperCAmelCase			:		Union[bool, str, TruncationStrategy] = None     ,      UpperCAmelCase			:		Optional[int] = None     ,      UpperCAmelCase			:		int = 0     ,      UpperCAmelCase			:		Optional[int] = None     ,      UpperCAmelCase			:		Optional[bool] = None     ,      UpperCAmelCase			:		Optional[bool] = None     ,      UpperCAmelCase			:		bool = False     ,      UpperCAmelCase			:		bool = False     ,      UpperCAmelCase			:		bool = False     ,      UpperCAmelCase			:		bool = False     ,      UpperCAmelCase			:		bool = True     ,      UpperCAmelCase			:		Optional[Union[str, TensorType]] = None     ,      **UpperCAmelCase			:		Any     ,      )  ->  BatchEncoding:


       '''simple docstring'''

       if self.image_processor.apply_ocr and (boxes is not None):
        raise ValueError(
            '''You cannot provide bounding boxes '''
            '''if you initialized the image processor with apply_ocr set to True.'''		)

       if self.image_processor.apply_ocr and (word_labels is not None):
        raise ValueError(
            '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'''		)

       if return_overflowing_tokens is True and return_offsets_mapping is False:
        raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.'''		)

       # first, apply the image processor
       lowercase					:   Tuple				  =self.image_processor(images=UpperCAmelCase     ,      return_tensors=UpperCAmelCase		)

       # second, apply the tokenizer
       if text is not None and self.image_processor.apply_ocr and text_pair is None:
        if isinstance(UpperCAmelCase     ,      UpperCAmelCase		):
         lowercase					:   Optional[Any]				  =[text]  # add batch dimension (as the image processor always adds a batch dimension)
        lowercase					:   List[str]				  =features['''words''']

       lowercase					:   Optional[Any]				  =self.tokenizer(
           text=text if text is not None else features['''words''']     ,      text_pair=text_pair if text_pair is not None else None     ,      boxes=boxes if boxes is not None else features['''boxes''']     ,      word_labels=UpperCAmelCase     ,      add_special_tokens=UpperCAmelCase     ,      padding=UpperCAmelCase     ,      truncation=UpperCAmelCase     ,      max_length=UpperCAmelCase     ,      stride=UpperCAmelCase     ,      pad_to_multiple_of=UpperCAmelCase     ,      return_token_type_ids=UpperCAmelCase     ,      return_attention_mask=UpperCAmelCase     ,      return_overflowing_tokens=UpperCAmelCase     ,      return_special_tokens_mask=UpperCAmelCase     ,      return_offsets_mapping=UpperCAmelCase     ,      return_length=UpperCAmelCase     ,      verbose=UpperCAmelCase     ,      return_tensors=UpperCAmelCase     ,      **UpperCAmelCase     ,      )

       # add pixel values
       lowercase					:   List[str]				  =features.pop('''pixel_values'''		)
       if return_overflowing_tokens is True:
        lowercase					:   str				  =self.get_overflowing_images(UpperCAmelCase     ,      encoded_inputs['''overflow_to_sample_mapping''']		)
       lowercase					:   Dict				  =images

       return encoded_inputs






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Optional[Any]     ,      UpperCAmelCase			:		str		)  ->  str:


       '''simple docstring'''

       lowercase					:   str				  =[]
       for sample_idx in overflow_to_sample_mapping:
        images_with_overflow.append(images[sample_idx]		)

       if len(UpperCAmelCase		) != len(UpperCAmelCase		):
        raise ValueError(
            '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'''
            f' {len(UpperCAmelCase		)} and {len(UpperCAmelCase		)}'		)

       return images_with_overflow






      def 				A__      ( self			:		Union[str, Any]     ,      *UpperCAmelCase			:		Tuple     ,      **UpperCAmelCase			:		Dict		)  ->  int:


       '''simple docstring'''

       return self.tokenizer.batch_decode(*UpperCAmelCase     ,      **UpperCAmelCase		)






      def 				A__      ( self			:		Dict     ,      *UpperCAmelCase			:		Any     ,      **UpperCAmelCase			:		Dict		)  ->  str:


       '''simple docstring'''

       return self.tokenizer.decode(*UpperCAmelCase     ,      **UpperCAmelCase		)






      @property
      def 				A__      ( self			:		List[str]		)  ->  List[str]:


       '''simple docstring'''

       return ["input_ids", "bbox", "attention_mask", "image"]






      @property
      def 				A__      ( self			:		int		)  ->  List[str]:


       '''simple docstring'''

       warnings.warn(
           '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''     ,      UpperCAmelCase     ,      )
       return self.image_processor_class






      @property
      def 				A__      ( self			:		Dict		)  ->  List[str]:


       '''simple docstring'''

       warnings.warn(
           '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''     ,      UpperCAmelCase     ,      )
       return self.image_processor



