




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


_lowerCamelCase					:     Optional[int]				       =    collections.namedtuple(
    'CheckpointState', ['model_dict', 'optimizer_dict', 'scheduler_dict', 'offset', 'epoch', 'encoder_params']
)

def 						lowercase_ (						_UpperCAmelCase		):




	"""simple docstring"""






	print(f"""Reading saved model from {model_file}"""		)
	A_					:			int						=						torch.load(_UpperCAmelCase					, map_location=lambda _UpperCAmelCase					, _UpperCAmelCase		: default_restore_location(_UpperCAmelCase					, '''cpu'''		)		)
	return CheckpointState(**_UpperCAmelCase		)

class     lowercase :







				def __init__(							self				:   str ,       _lowerCamelCase				:   Path    ):



					"""simple docstring"""

					A_					:			Optional[Any]						=						src_file







				def    a_					(							self				:   Tuple    ):



					"""simple docstring"""

					raise NotImplementedError







				@staticmethod
				def    a_					(							_lowerCamelCase				:   str ,       *_lowerCamelCase				:   int ,       **_lowerCamelCase				:   Optional[Any]    ):



					"""simple docstring"""

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

class     lowercase (      __UpperCAmelCase):







				def    a_					(							self				:   Union[str, Any]    ):



					"""simple docstring"""

					A_					:			Tuple						=						DPRContextEncoder(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_					:			Union[str, Any]						=						model.ctx_encoder, '''ctx_model.'''
					# Fix changes from https://github.com/huggingface/transformers/commit/614fef1691edb806de976756d4948ecbcd0c0ca3
					A_					:			Tuple						=						{'''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(_lowerCamelCase    ):
							A_					:			Union[str, Any]						=						key[len(_lowerCamelCase    ) :]
							if not key.startswith('''encode_proj.'''    ):
								A_					:			List[str]						=						'''bert_model.''' + key
							A_					:			Tuple						=						value
					encoder.load_state_dict(_lowerCamelCase    )
					return model

class     lowercase (      __UpperCAmelCase):







				def    a_					(							self				:   Union[str, Any]    ):



					"""simple docstring"""

					A_					:			Tuple						=						DPRQuestionEncoder(DPRConfig(**BertConfig.get_config_dict('''bert-base-uncased'''    )[0]    )    )
					print(F"""Loading DPR biencoder from {self.src_file}"""    )
					A_					:			Any						=						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_					:			Any						=						{'''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(_lowerCamelCase    ):
							A_					:			Optional[int]						=						key[len(_lowerCamelCase    ) :]
							if not key.startswith('''encode_proj.'''    ):
								A_					:			int						=						'''bert_model.''' + key
							A_					:			Optional[Any]						=						value
					encoder.load_state_dict(_lowerCamelCase    )
					return model

class     lowercase (      __UpperCAmelCase):







				def    a_					(							self				:   Dict    ):



					"""simple docstring"""

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

def 						lowercase_ (						_UpperCAmelCase					, _UpperCAmelCase					, _UpperCAmelCase		):




	"""simple docstring"""






	A_					:			Union[str, Any]						=						Path(_UpperCAmelCase		)
	dest_dir.mkdir(exist_ok=_UpperCAmelCase		)

	A_					:			Optional[Any]						=						DPRState.from_type(_UpperCAmelCase					, src_file=_UpperCAmelCase		)
	A_					:			List[Any]						=						dpr_state.load_dpr_model()
	model.save_pretrained(_UpperCAmelCase		)
	model.from_pretrained(_UpperCAmelCase		)  # sanity check


if __name__ == "__main__":
		_lowerCamelCase					:     List[str]				       =    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.')
		_lowerCamelCase					:     int				       =    parser.parse_args()

		_lowerCamelCase					:     Optional[int]				       =    Path(args.src)
		_lowerCamelCase					:     Union[str, Any]				       =    f'converted-{src_file.name}' if args.dest is None else args.dest
		_lowerCamelCase					:     Union[str, Any]				       =    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 bisect
import copy
from collections import defaultdict

import numpy as np
from torch.utils.data import BatchSampler, Sampler

from utils import logger

def 						lowercase_ (						_UpperCAmelCase					, _UpperCAmelCase		):




	"""simple docstring"""






	A_					:			Optional[int]						=						copy.deepcopy(_UpperCAmelCase		)
	A_					:			int						=						sorted(_UpperCAmelCase		)
	A_					:			Tuple						=						[bisect.bisect_right(_UpperCAmelCase					, _UpperCAmelCase		) for y in x]
	return quantized

def 						lowercase_ (						_UpperCAmelCase					, _UpperCAmelCase=0		):




	"""simple docstring"""






	A_					:			List[Any]						=						np.arange(start=3					, stop=_UpperCAmelCase					, step=4		).tolist() if k > 0 else [10]
	A_					:			List[Any]						=						_quantize(_UpperCAmelCase					, _UpperCAmelCase		)
	# count number of elements per group
	A_					:			Tuple						=						np.unique(_UpperCAmelCase					, return_counts=_UpperCAmelCase		)[1]
	A_					:			Optional[int]						=						[0] + bins + [np.inf]
	logger.info('''Using {} as bins for aspect lengths quantization'''.format(_UpperCAmelCase		)		)
	logger.info('''Count of instances per bin: {}'''.format(_UpperCAmelCase		)		)
	return groups

class     lowercase (      __UpperCAmelCase):







				def __init__(							self				:   Union[str, Any] ,       _lowerCamelCase				:   List[Any] ,       _lowerCamelCase				:   Dict ,       _lowerCamelCase				:   Dict    ):



					"""simple docstring"""

					if not isinstance(_lowerCamelCase ,       _lowerCamelCase    ):
						raise ValueError(
						    '''sampler should be an instance of torch.utils.data.Sampler, but got sampler={}'''.format(_lowerCamelCase    )    )
					A_					:			List[str]						=						sampler
					A_					:			str						=						group_ids
					A_					:			Any						=						batch_size







				def __iter__(							self				:   List[str]    ):



					"""simple docstring"""

					A_					:			List[str]						=						defaultdict(_lowerCamelCase    )
					A_					:			Dict						=						defaultdict(_lowerCamelCase    )

					A_					:			List[str]						=						0
					for idx in self.sampler:
						A_					:			Union[str, Any]						=						self.group_ids[idx]
						buffer_per_group[group_id].append(_lowerCamelCase    )
						samples_per_group[group_id].append(_lowerCamelCase    )
						if len(buffer_per_group[group_id]    ) == self.batch_size:
							yield buffer_per_group[group_id]  # TODO
							num_batches += 1
							del buffer_per_group[group_id]
						assert len(buffer_per_group[group_id]    ) < self.batch_size

					# now we have run out of elements that satisfy
					# the group criteria, let's return the remaining
					# elements so that the size of the sampler is
					# deterministic
					A_					:			int						=						len(self    )
					A_					:			Dict						=						expected_num_batches - num_batches
					if num_remaining > 0:
						# for the remaining batches, group the batches by similar lengths
						A_					:			Optional[Any]						=						[]
						for group_id, idxs in sorted(buffer_per_group.items() ,       key=lambda _lowerCamelCase    : x[0]    ):
							batch_idx.extend(_lowerCamelCase    )
							if len(_lowerCamelCase    ) >= self.batch_size:
								yield batch_idx[: self.batch_size]
								A_					:			str						=						batch_idx[self.batch_size :]
								num_remaining -= 1
						if len(_lowerCamelCase    ) > 0:
							yield batch_idx
							num_remaining -= 1
					assert num_remaining == 0







				def __len__(							self				:   List[Any]    ):



					"""simple docstring"""

					return (len(self.sampler    ) + self.batch_size - 1) // self.batch_size





