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







def       A__   (						snake_case_			:		str=2							,					snake_case_			:		Dict=3							,					snake_case_			:		List[str]=16							,					snake_case_			:		int = 10							,					snake_case_			:		int = 2   ):

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

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







def       A__   (						snake_case_			:		Optional[int]							,					snake_case_			:		Optional[int]							,					snake_case_			:		str							,					snake_case_			:		Union[str, Any]							,					snake_case_			:		int							,					snake_case_			:		str=None   ):
 SCREAMING_SNAKE_CASE__: Dict=   []
 for epoch in range(snake_case_   ):
  # Train quickly
  model.train()
  for batch in dataloader:
   SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Tuple=   batch
   SCREAMING_SNAKE_CASE__: Optional[Any]=   model(snake_case_   )
   SCREAMING_SNAKE_CASE__: List[Any]=   torch.nn.functional.mse_loss(snake_case_							,					snake_case_   )
   accelerator.backward(snake_case_   )
   optimizer.step()
   optimizer.zero_grad()
  rands.append(random.random()   )  # Introduce some randomness
  if scheduler is not None:
   scheduler.step()
 return rands






class 		_lowerCamelCase		( nn.Module     ):
    def __init__(	self )							->       str:
     super().__init__()
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   nn.Parameter(torch.randn(1 ) )
     SCREAMING_SNAKE_CASE__: Any=   nn.Parameter(torch.randn(1 ) )



    def     UpperCamelCase_					(	self			,			lowerCAmelCase )							->       str:
     return x * self.a + self.b






class 		_lowerCamelCase		( unittest.TestCase     ):
    def     UpperCamelCase_					(	self )							->       Tuple:
     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42 )
      SCREAMING_SNAKE_CASE__: Optional[Any]=   DummyModel()
      SCREAMING_SNAKE_CASE__: Optional[int]=   torch.optim.Adam(params=model.parameters()			,			lr=1e-3 )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Optional[int]=   dummy_dataloaders()
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   ProjectConfiguration(total_limit=1			,			project_dir=lowerCAmelCase			,			automatic_checkpoint_naming=lowerCAmelCase )
      # Train baseline
      SCREAMING_SNAKE_CASE__: Optional[int]=   Accelerator(project_config=lowerCAmelCase )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: str=   accelerator.prepare(
          lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      # 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]:
     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42 )
      SCREAMING_SNAKE_CASE__: Optional[int]=   DummyModel()
      SCREAMING_SNAKE_CASE__: Optional[int]=   torch.optim.Adam(params=model.parameters()			,			lr=1e-3 )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: str=   dummy_dataloaders()
      # Train baseline
      SCREAMING_SNAKE_CASE__: List[Any]=   Accelerator()
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Union[str, Any]=   accelerator.prepare(
          lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      # Save initial
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   os.path.join(lowerCAmelCase			,			'''initial''' )
      accelerator.save_state(lowerCAmelCase )
      ((SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__)): Tuple=   model.a.item(), model.b.item()
      SCREAMING_SNAKE_CASE__: Optional[int]=   optimizer.state_dict()
      SCREAMING_SNAKE_CASE__: Optional[int]=   train(3			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      ((SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__)): Tuple=   model.a.item(), model.b.item()
      SCREAMING_SNAKE_CASE__: Optional[int]=   optimizer.state_dict()

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

      SCREAMING_SNAKE_CASE__: Optional[int]=   train(2			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      # Save everything
      SCREAMING_SNAKE_CASE__: Optional[Any]=   os.path.join(lowerCAmelCase			,			'''checkpoint''' )
      accelerator.save_state(lowerCAmelCase )

      # Load everything back in and make sure all states work
      accelerator.load_state(lowerCAmelCase )
      test_rands += train(1			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      ((SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__)): Optional[Any]=   model.a.item(), model.b.item()
      SCREAMING_SNAKE_CASE__: Optional[Any]=   optimizer.state_dict()
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
    def     UpperCamelCase_					(	self )							->       str:
     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42 )
      SCREAMING_SNAKE_CASE__: List[Any]=   DummyModel()
      SCREAMING_SNAKE_CASE__: int=   torch.optim.Adam(params=model.parameters()			,			lr=1e-3 )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: int=   dummy_dataloaders()
      SCREAMING_SNAKE_CASE__: List[Any]=   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase )

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

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

      SCREAMING_SNAKE_CASE__: Dict=   train(2			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      # Save everything
      accelerator.save_state()

      # Load everything back in and make sure all states work
      accelerator.load_state(os.path.join(lowerCAmelCase			,			'''checkpoints'''			,			'''checkpoint_1''' ) )
      test_rands += train(1			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      ((SCREAMING_SNAKE_CASE__),						(SCREAMING_SNAKE_CASE__)): int=   model.a.item(), model.b.item()
      SCREAMING_SNAKE_CASE__: List[Any]=   optimizer.state_dict()
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
      self.assertEqual(lowerCAmelCase			,			lowerCAmelCase )
    def     UpperCamelCase_					(	self )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: Dict=   torch.tensor([1, 2, 3] )
     SCREAMING_SNAKE_CASE__: Dict=   torch.tensor([2, 3, 4] )
     SCREAMING_SNAKE_CASE__: int=   DummyModel()
     SCREAMING_SNAKE_CASE__: Optional[Any]=   torch.optim.Adam(net.parameters() )
     SCREAMING_SNAKE_CASE__: List[str]=   Accelerator()
     with self.assertRaises(lowerCAmelCase ) as ve:
      accelerator.register_for_checkpointing(lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
     SCREAMING_SNAKE_CASE__: 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     UpperCamelCase_					(	self )							->       Union[str, Any]:
     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42 )
      SCREAMING_SNAKE_CASE__: Tuple=   DummyModel()
      SCREAMING_SNAKE_CASE__: str=   torch.optim.Adam(params=model.parameters()			,			lr=1e-3 )
      SCREAMING_SNAKE_CASE__: List[Any]=   torch.optim.lr_scheduler.StepLR(lowerCAmelCase			,			step_size=1			,			gamma=0.99 )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Optional[Any]=   dummy_dataloaders()
      SCREAMING_SNAKE_CASE__: Optional[Any]=   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase )
      # Train baseline
      SCREAMING_SNAKE_CASE__: Any=   Accelerator(project_dir=lowerCAmelCase			,			project_config=lowerCAmelCase )
      SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__,						SCREAMING_SNAKE_CASE__: Tuple=   accelerator.prepare(
          lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      # Save initial
      accelerator.save_state()
      SCREAMING_SNAKE_CASE__: List[str]=   scheduler.state_dict()
      train(3			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )
      self.assertNotEqual(lowerCAmelCase			,			scheduler.state_dict() )

      # Load everything back in and make sure all states work
      accelerator.load_state(os.path.join(lowerCAmelCase			,			'''checkpoints'''			,			'''checkpoint_0''' ) )
      self.assertEqual(lowerCAmelCase			,			scheduler.state_dict() )
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     with tempfile.TemporaryDirectory() as tmpdir:
      set_seed(42 )
      SCREAMING_SNAKE_CASE__: str=   DummyModel()
      SCREAMING_SNAKE_CASE__: Tuple=   ProjectConfiguration(automatic_checkpoint_naming=lowerCAmelCase			,			total_limit=2 )
      # Train baseline
      SCREAMING_SNAKE_CASE__: List[str]=   Accelerator(project_dir=lowerCAmelCase			,			project_config=lowerCAmelCase )
      SCREAMING_SNAKE_CASE__: Union[str, Any]=   accelerator.prepare(lowerCAmelCase )
      # Save 3 states:
      for _ in range(11 ):
       accelerator.save_state()
      self.assertTrue(not os.path.exists(os.path.join(lowerCAmelCase			,			'''checkpoints'''			,			'''checkpoint_0''' ) ) )
      self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase			,			'''checkpoints'''			,			'''checkpoint_9''' ) ) )
      self.assertTrue(os.path.exists(os.path.join(lowerCAmelCase			,			'''checkpoints'''			,			'''checkpoint_10''' ) ) )



    @require_cuda
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__: Tuple=   ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )]
     execute_subprocess_async(lowerCAmelCase			,			env=os.environ.copy() )


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


A_				:      List[Any]           =			logging.get_logger(__name__)

A_				:      Optional[int]           =			{
    "facebook/dpr-ctx_encoder-single-nq-base": (
        "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
    ),
    "facebook/dpr-question_encoder-single-nq-base": (
        "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
    ),
    "facebook/dpr-reader-single-nq-base": (
        "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
    ),
    "facebook/dpr-ctx_encoder-multiset-base": (
        "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
    ),
    "facebook/dpr-question_encoder-multiset-base": (
        "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
    ),
    "facebook/dpr-reader-multiset-base": (
        "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
    ),
}





class  lowerCamelCase    (A__      ):
			lowerCamelCase__ :		Optional[int]       		=				'dpr'

			def __init__(       self					:    Optional[int]     ,					__UpperCAmelCase					:    List[str]=3_0_5_2_2     ,					__UpperCAmelCase					:    int=7_6_8     ,					__UpperCAmelCase					:    Optional[Any]=1_2     ,					__UpperCAmelCase					:    Dict=1_2     ,					__UpperCAmelCase					:    Any=3_0_7_2     ,					__UpperCAmelCase					:    int="gelu"     ,					__UpperCAmelCase					:    int=0.1     ,					__UpperCAmelCase					:    Optional[Any]=0.1     ,					__UpperCAmelCase					:    Any=5_1_2     ,					__UpperCAmelCase					:    Union[str, Any]=2     ,					__UpperCAmelCase					:    Any=0.02     ,					__UpperCAmelCase					:    Dict=1e-12     ,					__UpperCAmelCase					:    Optional[Any]=0     ,					__UpperCAmelCase					:    Union[str, Any]="absolute"     ,					__UpperCAmelCase					:    int = 0     ,					**__UpperCAmelCase					:    Dict     ,					) ->     Tuple:
						super().__init__(pad_token_id=__UpperCAmelCase     ,					**__UpperCAmelCase							)

						SCREAMING_SNAKE_CASE__										=   vocab_size
						SCREAMING_SNAKE_CASE__										=   hidden_size
						SCREAMING_SNAKE_CASE__										=   num_hidden_layers
						SCREAMING_SNAKE_CASE__										=   num_attention_heads
						SCREAMING_SNAKE_CASE__										=   hidden_act
						SCREAMING_SNAKE_CASE__										=   intermediate_size
						SCREAMING_SNAKE_CASE__										=   hidden_dropout_prob
						SCREAMING_SNAKE_CASE__										=   attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__										=   max_position_embeddings
						SCREAMING_SNAKE_CASE__										=   type_vocab_size
						SCREAMING_SNAKE_CASE__										=   initializer_range
						SCREAMING_SNAKE_CASE__										=   layer_norm_eps
						SCREAMING_SNAKE_CASE__										=   projection_dim
						SCREAMING_SNAKE_CASE__										=   position_embedding_type


