





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   (     a)			->CheckpointState:
					print(f"Reading saved model from {model_file}")
					lowerCamelCase__      =							torch.load(a,  map_location=lambda a,  a: default_restore_location(a,  "cpu"))
					return CheckpointState(**a)

class SCREAMING_SNAKE_CASE_			:





					"""simple docstring"""


					def __init__(			self						,	_lowerCAmelCase						):
										lowerCamelCase__      =							src_file





					def        __magic_name__			(			self						):
										raise NotImplementedError






					@staticmethod
					def        __magic_name__			(			_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 SCREAMING_SNAKE_CASE_			(       lowercase_ ):





					"""simple docstring"""


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

class SCREAMING_SNAKE_CASE_			(       lowercase_ ):





					"""simple docstring"""


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

class SCREAMING_SNAKE_CASE_			(       lowercase_ ):





					"""simple docstring"""


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





def  __UpperCamelCase   (     a,  a,  a)			->Optional[int]:
					lowerCamelCase__      =							Path(a)
					dest_dir.mkdir(exist_ok=a)

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








def  __UpperCamelCase   (     a = 998001)			->int:

					# fetches the next number
					for number in range(n - 1,  9999,  -1):
										lowerCamelCase__      =							str(a)

										# checks whether 'str_number' is a palindrome.
										if str_number == str_number[::-1]:
															lowerCamelCase__      =							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() = }""")

