




'''simple docstring'''


import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


lowerCAmelCase_			:     Optional[Any]							    =     get_logger(__name__)



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str   ,						UpperCamelCase__						:				List[dict]   ,						UpperCamelCase__						:				list   ,						UpperCamelCase__						:				list   ,						UpperCamelCase__						:				int   ,						UpperCamelCase__						:				GradScaler = None   ,						):




     """simple docstring"""


     for i, state in enumerate(UpperCamelCase__							):
          a_    :       List[Any]    	=     F"{MODEL_NAME}.bin" if i == 0 else F"{MODEL_NAME}_{i}.bin"
          a_    :       List[str]    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          save(UpperCamelCase__   ,						UpperCamelCase__							)
          logger.info(F"Model weights saved in {output_model_file}"							)
     # Optimizer states
     for i, opt in enumerate(UpperCamelCase__							):
          a_    :       Dict    	=     opt.state_dict()
          a_    :       Any    	=     F"{OPTIMIZER_NAME}.bin" if i == 0 else F"{OPTIMIZER_NAME}_{i}.bin"
          a_    :       Tuple    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          save(UpperCamelCase__   ,						UpperCamelCase__							)
          logger.info(F"Optimizer state saved in {output_optimizer_file}"							)
     # Scheduler states
     for i, scheduler in enumerate(UpperCamelCase__							):
          a_    :       int    	=     scheduler.state_dict()
          a_    :       Any    	=     F"{SCHEDULER_NAME}.bin" if i == 0 else F"{SCHEDULER_NAME}_{i}.bin"
          a_    :       int    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          save(UpperCamelCase__   ,						UpperCamelCase__							)
          logger.info(F"Scheduler state saved in {output_scheduler_file}"							)
     # GradScaler state
     if scaler is not None:
          a_    :       int    	=     scaler.state_dict()
          a_    :       List[str]    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          torch.save(UpperCamelCase__   ,						UpperCamelCase__							)
          logger.info(F"Gradient scaler state saved in {output_scaler_file}"							)
     # Random number generator states
     a_    :       List[Any]    	=     {}
     a_    :       List[Any]    	=     F"{RNG_STATE_NAME}_{process_index}.pkl"
     a_    :       Optional[Any]    	=     random.getstate()
     a_    :       int    	=     np.random.get_state()
     a_    :       List[Any]    	=     torch.get_rng_state()
     if is_xpu_available():
          a_    :       Optional[int]    	=     torch.xpu.get_rng_state_all()
     else:
          a_    :       List[str]    	=     torch.cuda.get_rng_state_all()
     if is_tpu_available():
          a_    :       str    	=     xm.get_rng_state()
     a_    :       int    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
     torch.save(UpperCamelCase__   ,						UpperCamelCase__							)
     logger.info(F"Random states saved in {output_states_file}"							)
     return output_dir



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				int   ,						UpperCamelCase__						:				Dict   ,						UpperCamelCase__						:				List[Any]   ,						UpperCamelCase__						:				Union[str, Any]   ,						UpperCamelCase__						:				List[str]   ,						UpperCamelCase__						:				Dict=None   ,						UpperCamelCase__						:				List[str]=None   ,						**UpperCamelCase__						:				int   ,						):




     """simple docstring"""


     if map_location not in [None, "cpu", "on_device"]:
          raise TypeError(
              """Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`"""							)
     if map_location is None:
          a_    :       Dict    	=     """cpu"""
     elif map_location == "on_device":
          a_    :       Optional[int]    	=     PartialState().device
     # Model states
     for i, model in enumerate(UpperCamelCase__							):
          a_    :       Dict    	=     F"{MODEL_NAME}.bin" if i == 0 else F"{MODEL_NAME}_{i}.bin"
          a_    :       Any    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          models[i].load_state_dict(torch.load(UpperCamelCase__   ,						map_location=UpperCamelCase__							)   ,						**UpperCamelCase__							)
     logger.info("""All model weights loaded successfully"""							)

     # Optimizer states
     for i, opt in enumerate(UpperCamelCase__							):
          a_    :       Optional[Any]    	=     F"{OPTIMIZER_NAME}.bin" if i == 0 else F"{OPTIMIZER_NAME}_{i}.bin"
          a_    :       Optional[int]    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          a_    :       Any    	=     torch.load(UpperCamelCase__   ,						map_location=UpperCamelCase__							)
          optimizers[i].load_state_dict(UpperCamelCase__							)
     logger.info("""All optimizer states loaded successfully"""							)

     # Scheduler states
     for i, scheduler in enumerate(UpperCamelCase__							):
          a_    :       str    	=     F"{SCHEDULER_NAME}.bin" if i == 0 else F"{SCHEDULER_NAME}_{i}.bin"
          a_    :       int    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          scheduler.load_state_dict(torch.load(UpperCamelCase__							)							)
     logger.info("""All scheduler states loaded successfully"""							)

     # GradScaler state
     if scaler is not None:
          a_    :       Any    	=     os.path.join(UpperCamelCase__   ,						UpperCamelCase__							)
          scaler.load_state_dict(torch.load(UpperCamelCase__							)							)
          logger.info("""GradScaler state loaded successfully"""							)

     # Random states
     try:
          a_    :       Dict    	=     torch.load(os.path.join(UpperCamelCase__   ,						F"{RNG_STATE_NAME}_{process_index}.pkl"							)							)
          random.setstate(states["""random_state"""]							)
          np.random.set_state(states["""numpy_random_seed"""]							)
          torch.set_rng_state(states["""torch_manual_seed"""]							)
          if is_xpu_available():
               torch.xpu.set_rng_state_all(states["""torch_xpu_manual_seed"""]							)
          else:
               torch.cuda.set_rng_state_all(states["""torch_cuda_manual_seed"""]							)
          if is_tpu_available():
               xm.set_rng_state(states["""xm_seed"""]							)
          logger.info("""All random states loaded successfully"""							)
     except Exception:
          logger.info("""Could not load random states"""							)



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[Any]   ,						UpperCamelCase__						:				Union[str, Any]   ,						UpperCamelCase__						:				int = 0							):




     """simple docstring"""


     a_    :       Tuple    	=     Path(UpperCamelCase__							) / F"custom_checkpoint_{index}.pkl"
     logger.info(F"Saving the state of {get_pretty_name(UpperCamelCase__							)} to {save_location}"							)
     torch.save(obj.state_dict()   ,						UpperCamelCase__							)



def    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				Optional[int]   ,						UpperCamelCase__						:				Tuple   ,						UpperCamelCase__						:				int = 0							):




     """simple docstring"""


     a_    :       Tuple    	=     F"{path}/custom_checkpoint_{index}.pkl"
     logger.info(F"Loading the state of {get_pretty_name(UpperCamelCase__							)} from {load_location}"							)
     obj.load_state_dict(torch.load(UpperCamelCase__   ,						map_location="""cpu"""							)							)






'''simple docstring'''


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowerCAmelCase_			:     int							    =     {
    'configuration_dpr': ['DPR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DPRConfig'],
    'tokenization_dpr': [
        'DPRContextEncoderTokenizer',
        'DPRQuestionEncoderTokenizer',
        'DPRReaderOutput',
        'DPRReaderTokenizer',
    ],
}


try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     Union[str, Any]							    =     [
     'DPRContextEncoderTokenizerFast',
     'DPRQuestionEncoderTokenizerFast',
     'DPRReaderTokenizerFast',
 ]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     List[str]							    =     [
     'DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'DPRContextEncoder',
     'DPRPretrainedContextEncoder',
     'DPRPreTrainedModel',
     'DPRPretrainedQuestionEncoder',
     'DPRPretrainedReader',
     'DPRQuestionEncoder',
     'DPRReader',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 lowerCAmelCase_			:     Dict							    =     [
     'TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFDPRContextEncoder',
     'TFDPRPretrainedContextEncoder',
     'TFDPRPretrainedQuestionEncoder',
     'TFDPRPretrainedReader',
     'TFDPRQuestionEncoder',
     'TFDPRReader',
 ]


if TYPE_CHECKING:
 from .configuration_dpr import DPR_PRETRAINED_CONFIG_ARCHIVE_MAP, DPRConfig
 from .tokenization_dpr import (
     DPRContextEncoderTokenizer,
     DPRQuestionEncoderTokenizer,
     DPRReaderOutput,
     DPRReaderTokenizer,
 )

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_dpr_fast import (
      DPRContextEncoderTokenizerFast,
      DPRQuestionEncoderTokenizerFast,
      DPRReaderTokenizerFast,
  )

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_dpr import (
      DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
      DPRContextEncoder,
      DPRPretrainedContextEncoder,
      DPRPreTrainedModel,
      DPRPretrainedQuestionEncoder,
      DPRPretrainedReader,
      DPRQuestionEncoder,
      DPRReader,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_dpr import (
      TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFDPRContextEncoder,
      TFDPRPretrainedContextEncoder,
      TFDPRPretrainedQuestionEncoder,
      TFDPRPretrainedReader,
      TFDPRQuestionEncoder,
      TFDPRReader,
  )

else:
 import sys

 lowerCAmelCase_			:     int							    =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
