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__  	=      collections.namedtuple(
    "CheckpointState", ["model_dict", "optimizer_dict", "scheduler_dict", "offset", "epoch", "encoder_params"]
)

def 	__lowerCamelCase							(				__a    : str		)      ->       CheckpointState:
	print(f'''Reading saved model from {model_file}'''		)
	_lowercase   =torch.load(__a      ,							map_location=lambda __a      ,							__a		: default_restore_location(__a      ,							"cpu"		)		)
	return CheckpointState(**__a		)
class 	_a  :



	"""simple docstring"""



	def __init__(   self       ,  lowerCAmelCase_       ):
		_lowercase   =src_file


	def __lowerCAmelCase      (   self       ):
		raise NotImplementedError


	@staticmethod
	def __lowerCAmelCase      (   lowerCAmelCase_       ,  *lowerCAmelCase_       ,  **lowerCAmelCase_       ):
		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 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



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

def 	__lowerCamelCase							(				__a    : str      ,							__a    : Path      ,							__a    : Path		)      ->       int:
	_lowercase   =Path(__a		)
	dest_dir.mkdir(exist_ok=__a		)

	_lowercase   =DPRState.from_type(__a      ,							src_file=__a		)
	_lowercase   =dpr_state.load_dpr_model()
	model.save_pretrained(__a		)
	model.from_pretrained(__a		)  # sanity check


if __name__ == "__main__":
						lowerCAmelCase__  	=      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__  	=      parser.parse_args()

						lowerCAmelCase__  	=      Path(args.src)
						lowerCAmelCase__  	=      F'''converted-{src_file.name}''' if args.dest is None else args.dest
						lowerCAmelCase__  	=      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)









def    UpperCAmelCase					(  lowercase__						:					int = 998001	):



			'''simple docstring'''





			for number in range(n - 1				,					9999				,					-1	):
						a__					=  str(lowercase__	)

						# checks whether 'str_number' is a palindrome.
						if str_number == str_number[::-1]:
									a__					=  999

									# if 'number' is a product of two 3-digit numbers
									# then number is the answer otherwise fetch next number.
									while divisor != 99:
												if (number % divisor == 0) and (len(str(number // divisor	)	) == 3.0):
															return number
												divisor -= 1
			raise ValueError("""That number is larger than our acceptable range."""	)


if __name__ == "__main__":
	print(f'''{solution() = }''')

