






'''simple docstring'''





import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


a_      = logging.get_logger(__name__)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



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






								'''simple docstring'''


								super().__init__()
								if version.parse(torch.__version__) < version.parse("1.12.0"):
														raise ImportError(
														    f"""You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use """
														    "PytorchGELUTanh. Please upgrade torch.")




		def _lowerCAmelCase     (    self:    Dict				,   a:    Dict)  ->Union[str, Any]:






								'''simple docstring'''


								return nn.functional.gelu(_lowerCamelCase				,   approximate="tanh")





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    List[str]				,   a:    Tuple)  ->List[Any]:






								'''simple docstring'''


								return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.04_4715 * torch.pow(_lowerCamelCase				,   3.0))))





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def __init__(    self:    Dict				,   a:    List[Any] = False)  ->List[Any]:






								'''simple docstring'''


								super().__init__()
								if use_gelu_python:
														a_				     =   self._gelu_python
								else:
														a_				     =   nn.functional.gelu



		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Tuple)  ->Union[str, Any]:






								'''simple docstring'''


								return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))




		def _lowerCAmelCase     (    self:    Tuple				,   a:    Tuple)  ->int:






								'''simple docstring'''


								return self.act(_lowerCamelCase)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    List[str]				,   a:    Optional[int])  ->Optional[int]:






								'''simple docstring'''


								return 0.5 * input * (1.0 + torch.tanh(input * 0.79_7884_5608 * (1.0 + 0.04_4715 * input * input)))





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    Union[str, Any]				,   a:    Any)  ->Any:






								'''simple docstring'''


								return input * torch.sigmoid(1.702 * input)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def __init__(    self:    List[Any]				,   a:    List[str]				,   a:    Tuple)  ->int:






								'''simple docstring'''


								if min > max:
														raise ValueError(f"""min should be < max (got min: {min}, max: {max})""")

								super().__init__()
								a_				     =   min
								a_				     =   max




		def _lowerCAmelCase     (    self:    List[Any]				,   a:    Dict)  ->int:






								'''simple docstring'''


								return torch.clip(gelu(_lowerCamelCase)				,   self.min				,   self.max)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



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






								'''simple docstring'''


								super().__init__()
								a_				     =   math.sqrt(2 / math.pi)




		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Optional[int])  ->int:






								'''simple docstring'''


								return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.04_4715 * torch.pow(_lowerCamelCase				,   3))))





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    int				,   a:    List[Any])  ->Union[str, Any]:






								'''simple docstring'''


								return nn.functional.silu(_lowerCamelCase)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



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






								'''simple docstring'''


								super().__init__()
								if version.parse(torch.__version__) < version.parse("1.9.0"):
														a_				     =   self._mish_python
								else:
														a_				     =   nn.functional.mish



		def _lowerCAmelCase     (    self:    str				,   a:    List[Any])  ->Optional[int]:






								'''simple docstring'''


								return input * torch.tanh(nn.functional.softplus(_lowerCamelCase))




		def _lowerCAmelCase     (    self:    Any				,   a:    Dict)  ->str:






								'''simple docstring'''


								return self.act(_lowerCamelCase)





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    Optional[Any]				,   a:    Optional[Any])  ->Optional[int]:






								'''simple docstring'''


								return input





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    Dict				,   a:    Optional[int]				,   a:    Optional[Any]=0.70_7107				,   a:    List[Any]=0.28_2095)  ->List[Any]:






								'''simple docstring'''


								a_				     =   (input - mu).div(sigma * math.sqrt(2.0))
								return 0.5 * (1.0 + torch.erf(_lowerCamelCase))





class 		SCREAMING_SNAKE_CASE__   (     nn.Module    ):



		def _lowerCAmelCase     (    self:    List[str]				,   a:    int)  ->str:






								'''simple docstring'''


								a_				     =   nn.functional.relu(_lowerCamelCase)
								a_				     =   torch.square(_lowerCamelCase)
								return squared





class 		SCREAMING_SNAKE_CASE__   (     lowerCAmelCase__    ):



		def __getitem__(    self:    Any				,   a:    Optional[Any])  ->Optional[int]:






								'''simple docstring'''


								a_				     =   super().__getitem__(_lowerCamelCase)
								a_				     =   content if isinstance(_lowerCamelCase				,   _lowerCamelCase) else (content, {})
								return cls(**_lowerCamelCase)





a_      = {
    'gelu': GELUActivation,
    'gelu_10': (ClippedGELUActivation, {'min': -10, 'max': 10}),
    'gelu_fast': FastGELUActivation,
    'gelu_new': NewGELUActivation,
    'gelu_python': (GELUActivation, {'use_gelu_python': True}),
    'gelu_pytorch_tanh': PytorchGELUTanh,
    'gelu_accurate': AccurateGELUActivation,
    'laplace': LaplaceActivation,
    'linear': LinearActivation,
    'mish': MishActivation,
    'quick_gelu': QuickGELUActivation,
    'relu': nn.ReLU,
    'relu2': ReLUSquaredActivation,
    'relu6': nn.ReLUa,
    'sigmoid': nn.Sigmoid,
    'silu': SiLUActivation,
    'swish': SiLUActivation,
    'tanh': nn.Tanh,
}
a_      = ClassInstantier(ACTaCLS)



def 			__UpperCAmelCase				(lowercase__				)		->				Union[str, Any]:

						'''simple docstring'''


						if activation_string in ACTaFN:
												return ACTaFN[activation_string]
						else:
												raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()				)}"""				)


# For backwards compatibility with: from activations import gelu_python
a_      = get_activation('gelu_python')
a_      = get_activation('gelu_new')
a_      = get_activation('gelu')
a_      = get_activation('gelu_fast')
a_      = get_activation('quick_gelu')
a_      = get_activation('silu')
a_      = get_activation('mish')
a_      = get_activation('linear')














'''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 			__UpperCAmelCase				(lowercase__				)		->				CheckpointState:

						'''simple docstring'''


						print(F"""Reading saved model from {model_file}"""				)
						a_				     =   torch.load(lowercase__	,map_location=lambda lowercase__	,lowercase__				: default_restore_location(lowercase__	,"cpu"				)				)
						return CheckpointState(**lowercase__				)





class 		SCREAMING_SNAKE_CASE__   :



		def __init__(    self:    int				,   a:    Path)  ->str:






								'''simple docstring'''


								a_				     =   src_file



		def _lowerCAmelCase     (    self:    Dict)  ->Optional[Any]:






								'''simple docstring'''


								raise NotImplementedError




		@staticmethod
		def _lowerCAmelCase     (    a:    str				,   *a:    int				,   **a:    int)  ->"DPRState":






								'''simple docstring'''


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





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



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






								'''simple docstring'''


								a_				     =   DPRContextEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR biencoder from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								a_     ,       a_				     =   model.ctx_encoder, "ctx_model."
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {"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(a):
																				a_				     =   key[len(a) :]
																				if not key.startswith("encode_proj."):
																										a_				     =   "bert_model." + key
																				a_				     =   value
								encoder.load_state_dict(a)
								return model





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Optional[int])  ->Optional[int]:






								'''simple docstring'''


								a_				     =   DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR biencoder from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								a_     ,       a_				     =   model.question_encoder, "question_model."
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {"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(a):
																				a_				     =   key[len(a) :]
																				if not key.startswith("encode_proj."):
																										a_				     =   "bert_model." + key
																				a_				     =   value
								encoder.load_state_dict(a)
								return model





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



		def _lowerCAmelCase     (    self:    Tuple)  ->Optional[Any]:






								'''simple docstring'''


								a_				     =   DPRReader(DPRConfig(**BertConfig.get_config_dict("bert-base-uncased")[0]))
								print(f"""Loading DPR reader from {self.src_file}""")
								a_				     =   load_states_from_checkpoint(self.src_file)
								# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
								a_				     =   {
								    "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_				     =   "encoder.bert_model." + key[len("encoder.") :]
														a_				     =   value
								model.span_predictor.load_state_dict(a)
								return model





def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				Any:

						'''simple docstring'''


						a_				     =   Path(lowercase__				)
						dest_dir.mkdir(exist_ok=lowercase__				)

						a_				     =   DPRState.from_type(lowercase__	,src_file=lowercase__				)
						a_				     =   dpr_state.load_dpr_model()
						model.save_pretrained(lowercase__				)
						model.from_pretrained(lowercase__				)  # 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)



