






'''simple docstring'''





from functools import partial
from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload

import torch
import torch.nn as nn
import torch.types



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						if not inplace:
												a_				     =   ma + ma
						else:
												ma += ma

						return ma



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   -1 * len(lowercase__				)
						a_				     =   list(range(len(tensor.shape[:zero_index]				)				)				)
						return tensor.permute(first_inds + [zero_index + i for i in inds]				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						return t.reshape(t.shape[:-no_dims] + (-1,)				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__	,lowercase__ = 1e-4				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   mask.expand(*value.shape				)
						return torch.sum(mask * value	,dim=lowercase__				) / (eps + torch.sum(lowercase__	,dim=lowercase__				))



def 			__UpperCAmelCase				(lowercase__	,lowercase__ = 2.3125	,lowercase__ = 21.6875	,lowercase__ = 64				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   torch.linspace(lowercase__	,lowercase__	,no_bins - 1	,device=pts.device				)
						a_				     =   torch.sqrt(torch.sum((pts.unsqueeze(-2				) - pts.unsqueeze(-3				)) ** 2	,dim=-1				)				)
						return torch.bucketize(lowercase__	,lowercase__				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				dict:

						'''simple docstring'''


						a_				     =   dicts[0]
						a_				     =   {}
						for k, v in first.items():
												a_				     =   [d[k] for d in dicts]
												if isinstance(lowercase__	,lowercase__				):
																		a_				     =   dict_multimap(lowercase__	,lowercase__				)
												else:
																		a_				     =   fn(lowercase__				)

						return new_dict



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   v_bins.view(((1,) * len(x.shape				)) + (len(lowercase__				),)				)
						a_				     =   x[..., None] - reshaped_bins
						a_				     =   torch.argmin(torch.abs(lowercase__				)	,dim=-1				)
						return nn.functional.one_hot(lowercase__	,num_classes=len(lowercase__				)				).float()



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__ = 0	,lowercase__ = 0				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   []
						for i, s in enumerate(data.shape[:no_batch_dims]				):
												a_				     =   torch.arange(lowercase__				)
												a_				     =   r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape				) - i - 1)))				)
												ranges.append(lowercase__				)

						a_				     =   [slice(lowercase__				) for _ in range(len(data.shape				) - no_batch_dims				)]
						a_				     =   inds
						ranges.extend(lowercase__				)
						# Matt note: Editing this to get around the behaviour of using a list as an array index changing
						# in recent Numpy versions
						return data[tuple(lowercase__				)]


a_      = TypeVar('T')



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				Dict[Any, Union[dict, list, tuple, Any]]:

						'''simple docstring'''


						a_				     =   {}
						for k, v in dic.items():
												if isinstance(lowercase__	,lowercase__				):
																		a_				     =   dict_map(lowercase__	,lowercase__	,lowercase__				)
												else:
																		a_				     =   tree_map(lowercase__	,lowercase__	,lowercase__				)

						return new_dict



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

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				dict:

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				list:

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				tuple:

						'''simple docstring'''


						...



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

						'''simple docstring'''


						if isinstance(lowercase__	,lowercase__				):
												return dict_map(lowercase__	,lowercase__	,lowercase__				)
						elif isinstance(lowercase__	,lowercase__				):
												return [tree_map(lowercase__	,lowercase__	,lowercase__				) for x in tree]
						elif isinstance(lowercase__	,lowercase__				):
												return tuple(tree_map(lowercase__	,lowercase__	,lowercase__				) for x in tree				)
						elif isinstance(lowercase__	,lowercase__				):
												return fn(lowercase__				)
						else:
												print(type(lowercase__				)				)
												raise ValueError("Not supported"				)
a_      = partial(tree_map, leaf_type=torch.Tensor)














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



