






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


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

def    lowerCAmelCase__		(			_a				:	str			):
		print(F'''Reading saved model from {model_file}'''			)
		snake_case_ :							Optional[int]         =				torch.load(_a     ,					map_location=lambda _a     ,					_a			: default_restore_location(_a     ,					"cpu"			)			)
		return CheckpointState(**_a			)




class 						UpperCAmelCase_  :


						'''simple docstring'''




						def __init__(		self						, _SCREAMING_SNAKE_CASE )       -> Optional[Any]:
								snake_case_ :							List[Any]         =				src_file






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






						@staticmethod
						def 					_lowerCAmelCase				(		_SCREAMING_SNAKE_CASE						, *_SCREAMING_SNAKE_CASE						, **_SCREAMING_SNAKE_CASE )       -> "DPRState":
								if comp_type.startswith("c" ):
										return DPRContextEncoderState(*_SCREAMING_SNAKE_CASE						, **_SCREAMING_SNAKE_CASE )
								if comp_type.startswith("q" ):
										return DPRQuestionEncoderState(*_SCREAMING_SNAKE_CASE						, **_SCREAMING_SNAKE_CASE )
								if comp_type.startswith("r" ):
										return DPRReaderState(*_SCREAMING_SNAKE_CASE						, **_SCREAMING_SNAKE_CASE )
								else:
										raise ValueError("Component type must be either 'ctx_encoder', 'question_encoder' or 'reader'." )




class 						UpperCAmelCase_  (		SCREAMING_SNAKE_CASE__    ):


						'''simple docstring'''




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




class 						UpperCAmelCase_  (		SCREAMING_SNAKE_CASE__    ):


						'''simple docstring'''




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




class 						UpperCAmelCase_  (		SCREAMING_SNAKE_CASE__    ):


						'''simple docstring'''




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




def    lowerCAmelCase__		(			_a				:	str     ,					_a				:	Path     ,					_a				:	Path			):
		snake_case_ :							Optional[int]         =				Path(_a			)
		dest_dir.mkdir(exist_ok=_a			)

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


if __name__ == "__main__":
							lowercase     :							Dict	     =			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.''')
							lowercase     :							Tuple	     =			parser.parse_args()

							lowercase     :							Dict	     =			Path(args.src)
							lowercase     :							Optional[int]	     =			F"""converted-{src_file.name}""" if args.dest is None else args.dest
							lowercase     :							Dict	     =			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)








from __future__ import annotations

def    lowerCAmelCase__		(			_a				:	list[int]     ,					_a				:	int			):
		snake_case_       ,				snake_case_ :							Tuple         =				0, len(_a			) - 1
		while start_ind <= end_ind:
				if array[start_ind] == search_item:
						return start_ind
				elif array[end_ind] == search_item:
						return end_ind
				else:
						start_ind += 1
						end_ind -= 1
    # returns -1 if search_item is not found in array
		return -1


if __name__ == "__main__":
							print(double_linear_search(list(range(1_00)), 40))
