






"""simple docstring"""



import argparse
import collections
from pathlib import Path

import torch
from torch.serialization import default_restore_location

from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader


A_     =				collections.namedtuple(
    '''CheckpointState''', ['''model_dict''', '''optimizer_dict''', '''scheduler_dict''', '''offset''', '''epoch''', '''encoder_params''']
)




def   _lowerCAmelCase		(				UpperCAmelCase__							:       str   )		->CheckpointState:
						print(f'Reading saved model from {model_file}'   )
						A__    :	Any			=	torch.load(UpperCAmelCase__,    map_location=lambda UpperCAmelCase__,    UpperCAmelCase__   : default_restore_location(UpperCAmelCase__,    """cpu"""   )   )
						return CheckpointState(**UpperCAmelCase__   )






class 				__SCREAMING_SNAKE_CASE    :


							def __init__(      self   :    List[Any]      ,     snake_case   :    Path				):
													'''simple docstring'''





													A__    :	Optional[int]			=	src_file


							def     _UpperCamelCase							(      self   :    Tuple				):
													'''simple docstring'''





													raise NotImplementedError


							@staticmethod
							def     _UpperCamelCase							(      snake_case   :    str      ,     *snake_case   :    str      ,     **snake_case   :    Dict				):
													'''simple docstring'''





													if comp_type.startswith("""c"""				):
																			return DPRContextEncoderState(*snake_case      ,     **snake_case				)
													if comp_type.startswith("""q"""				):
																			return DPRQuestionEncoderState(*snake_case      ,     **snake_case				)
													if comp_type.startswith("""r"""				):
																			return DPRReaderState(*snake_case      ,     **snake_case				)
													else:
																			raise ValueError("""Component type must be either 'ctx_encoder', 'question_encoder' or 'reader'."""				)






class 				__SCREAMING_SNAKE_CASE    (					UpperCamelCase		):


							def     _UpperCamelCase							(      self   :    List[str]				):
													'''simple docstring'''





													A__    :	str			=	DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""				)[0]				)				)
													print(F'Loading DPR biencoder from {self.src_file}'				)
													A__    :	Union[str, Any]			=	load_states_from_checkpoint(self.src_file				)
													A__	,	A__    :	Dict			=	model.ctx_encoder, """ctx_model."""
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													A__    :	List[str]			=	{"""bert_model.embeddings.position_ids""": model.ctx_encoder.bert_model.embeddings.position_ids}
													for key, value in saved_state.model_dict.items():
																			if key.startswith(snake_case				):
																									A__    :	List[Any]			=	key[len(snake_case				) :]
																									if not key.startswith("""encode_proj."""				):
																															A__    :	Tuple			=	"""bert_model.""" + key
																									A__    :	List[Any]			=	value
													encoder.load_state_dict(snake_case				)
													return model






class 				__SCREAMING_SNAKE_CASE    (					UpperCamelCase		):


							def     _UpperCamelCase							(      self   :    Any				):
													'''simple docstring'''





													A__    :	List[str]			=	DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""				)[0]				)				)
													print(F'Loading DPR biencoder from {self.src_file}'				)
													A__    :	Dict			=	load_states_from_checkpoint(self.src_file				)
													A__	,	A__    :	Any			=	model.question_encoder, """question_model."""
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													A__    :	List[str]			=	{"""bert_model.embeddings.position_ids""": model.question_encoder.bert_model.embeddings.position_ids}
													for key, value in saved_state.model_dict.items():
																			if key.startswith(snake_case				):
																									A__    :	List[str]			=	key[len(snake_case				) :]
																									if not key.startswith("""encode_proj."""				):
																															A__    :	Union[str, Any]			=	"""bert_model.""" + key
																									A__    :	List[str]			=	value
													encoder.load_state_dict(snake_case				)
													return model






class 				__SCREAMING_SNAKE_CASE    (					UpperCamelCase		):


							def     _UpperCamelCase							(      self   :    str				):
													'''simple docstring'''





													A__    :	List[Any]			=	DPRReader(DPRConfig(**BertConfig.get_config_dict("""bert-base-uncased"""				)[0]				)				)
													print(F'Loading DPR reader from {self.src_file}'				)
													A__    :	Any			=	load_states_from_checkpoint(self.src_file				)
													# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
													A__    :	Tuple			=	{
													    """encoder.bert_model.embeddings.position_ids""": model.span_predictor.encoder.bert_model.embeddings.position_ids
													}
													for key, value in saved_state.model_dict.items():
																			if key.startswith("""encoder."""				) and not key.startswith("""encoder.encode_proj"""				):
																									A__    :	Optional[int]			=	"""encoder.bert_model.""" + key[len("""encoder."""				) :]
																			A__    :	str			=	value
													model.span_predictor.load_state_dict(snake_case				)
													return model




def   _lowerCAmelCase		(				UpperCAmelCase__							:       str,    UpperCAmelCase__							:       Path,    UpperCAmelCase__							:       Path   )		->Dict:
						A__    :	str			=	Path(UpperCAmelCase__   )
						dest_dir.mkdir(exist_ok=UpperCAmelCase__   )

						A__    :	Optional[int]			=	DPRState.from_type(UpperCAmelCase__,    src_file=UpperCAmelCase__   )
						A__    :	Tuple			=	dpr_state.load_dpr_model()
						model.save_pretrained(UpperCAmelCase__   )
						model.from_pretrained(UpperCAmelCase__   )  # sanity check


if __name__ == "__main__":
						A_     =				argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--type''', type=str, help='''Type of the component to convert: \'ctx_encoder\', \'question_encoder\' or \'reader\'.'''
						)
						parser.add_argument(
						    '''--src''',
						    type=str,
						    help=(
						        '''Path to the dpr checkpoint file. They can be downloaded from the official DPR repo'''
						        ''' https://github.com/facebookresearch/DPR. Note that in the official repo, both encoders are stored in the'''
						        ''' \'retriever\' checkpoints.'''
						    ),
						)
						parser.add_argument('''--dest''', type=str, default=None, help='''Path to the output PyTorch model directory.''')
						A_     =				parser.parse_args()

						A_     =				Path(args.src)
						A_     =				F'converted-{src_file.name}' if args.dest is None else args.dest
						A_     =				Path(dest_dir)
						assert src_file.exists()
						assert (
						    args.type is not None
						), "Please specify the component type of the DPR model to convert: 'ctx_encoder', 'question_encoder' or 'reader'."
						convert(args.type, src_file, dest_dir)














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


A_     =				get_logger(__name__)




def   _lowerCAmelCase		(				UpperCAmelCase__							:       str,    UpperCAmelCase__							:       List[dict],    UpperCAmelCase__							:       list,    UpperCAmelCase__							:       list,    UpperCAmelCase__							:       int,    UpperCAmelCase__							:       GradScaler = None,    )		->Any:
						# Model states
						for i, state in enumerate(UpperCAmelCase__   ):
												A__    :	Optional[int]			=	f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
												A__    :	int			=	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__    :	str			=	opt.state_dict()
												A__    :	Any			=	f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
												A__    :	Optional[int]			=	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__    :	Union[str, Any]			=	scheduler.state_dict()
												A__    :	Union[str, Any]			=	f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
												A__    :	Tuple			=	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__    :	List[str]			=	scaler.state_dict()
												A__    :	Optional[Any]			=	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__    :	str			=	{}
						A__    :	str			=	f'{RNG_STATE_NAME}_{process_index}.pkl'
						A__    :	Optional[Any]			=	random.getstate()
						A__    :	str			=	np.random.get_state()
						A__    :	List[str]			=	torch.get_rng_state()
						if is_xpu_available():
												A__    :	Optional[Any]			=	torch.xpu.get_rng_state_all()
						else:
												A__    :	str			=	torch.cuda.get_rng_state_all()
						if is_tpu_available():
												A__    :	Tuple			=	xm.get_rng_state()
						A__    :	str			=	os.path.join(UpperCAmelCase__,    UpperCAmelCase__   )
						torch.save(UpperCAmelCase__,    UpperCAmelCase__   )
						logger.info(f'Random states saved in {output_states_file}'   )
						return output_dir




def   _lowerCAmelCase		(				UpperCAmelCase__							:       Any,    UpperCAmelCase__							:       Union[str, Any],    UpperCAmelCase__							:       Union[str, Any],    UpperCAmelCase__							:       Dict,    UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       Optional[Any]=None,    UpperCAmelCase__							:       str=None,    **UpperCAmelCase__							:       Optional[int],    )		->List[str]:
						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__    :	Union[str, Any]			=	"""cpu"""
						elif map_location == "on_device":
												A__    :	Any			=	PartialState().device
						# Model states
						for i, model in enumerate(UpperCAmelCase__   ):
												A__    :	Any			=	f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
												A__    :	List[str]			=	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__    :	Union[str, Any]			=	f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
												A__    :	Dict			=	os.path.join(UpperCAmelCase__,    UpperCAmelCase__   )
												A__    :	List[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__    :	List[Any]			=	f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
												A__    :	Optional[Any]			=	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__    :	List[str]			=	os.path.join(UpperCAmelCase__,    UpperCAmelCase__   )
												scaler.load_state_dict(torch.load(UpperCAmelCase__   )   )
												logger.info("""GradScaler state loaded successfully"""   )

						# Random states
						try:
												A__    :	Any			=	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   _lowerCAmelCase		(				UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       Dict,    UpperCAmelCase__							:       int = 0   )		->Dict:
						A__    :	Dict			=	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   _lowerCAmelCase		(				UpperCAmelCase__							:       Tuple,    UpperCAmelCase__							:       str,    UpperCAmelCase__							:       int = 0   )		->str:
						A__    :	Optional[int]			=	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"""   )   )






