






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






def 						_SCREAMING_SNAKE_CASE							( UpperCamelCase     :	str    ):
  print(F"""Reading saved model from {model_file}"""    )
  A__											=							torch.load(UpperCamelCase		,				map_location=lambda UpperCamelCase		,				UpperCamelCase    : default_restore_location(UpperCamelCase		,				"""cpu"""    )    )
  return CheckpointState(**UpperCamelCase    )







class 					_UpperCamelCase		:






    def __init__(self						,      lowerCamelCase__   ):


      """simple docstring"""
      A__											=							src_file






    def  A    (self   ):


      """simple docstring"""
      raise NotImplementedError






    @staticmethod
    def  A    (lowerCamelCase__						,      *lowerCamelCase__						,      **lowerCamelCase__   ):


      """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 					_UpperCamelCase		( __snake_case):






    def  A    (self   ):


      """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(lowerCamelCase__   ):
          A__											=							key[len(lowerCamelCase__   ) :]
          if not key.startswith("""encode_proj."""   ):
            A__											=							"""bert_model.""" + key
          A__											=							value
      encoder.load_state_dict(lowerCamelCase__   )
      return model







class 					_UpperCamelCase		( __snake_case):






    def  A    (self   ):


      """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(lowerCamelCase__   ):
          A__											=							key[len(lowerCamelCase__   ) :]
          if not key.startswith("""encode_proj."""   ):
            A__											=							"""bert_model.""" + key
          A__											=							value
      encoder.load_state_dict(lowerCamelCase__   )
      return model







class 					_UpperCamelCase		( __snake_case):






    def  A    (self   ):


      """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(lowerCamelCase__   )
      return model






def 						_SCREAMING_SNAKE_CASE							( UpperCamelCase     :	str		,				UpperCamelCase     :	Path		,				UpperCamelCase     :	Path    ):
  A__											=							Path(UpperCamelCase    )
  dest_dir.mkdir(exist_ok=UpperCamelCase    )

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












"""simple docstring"""




from .hash_table import HashTable
from .number_theory.prime_numbers import is_prime, next_prime







class 					_UpperCamelCase		( __snake_case):






    def __init__(self						,      *lowerCamelCase__						,      **lowerCamelCase__   ):


      """simple docstring"""
      super().__init__(*lowerCamelCase__						,      **lowerCamelCase__   )






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__   ):


      """simple docstring"""
      A__											=							(
          next_prime(value % self.size_table   )
          if not is_prime(value % self.size_table   )
          else value % self.size_table
      )  # gt = bigger than
      return next_prime_gt - (data % next_prime_gt)






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   ):


      """simple docstring"""
      return (increment * self.__hash_function_a(lowerCamelCase__						,      lowerCamelCase__   )) % self.size_table






    def  A    (self						,      lowerCamelCase__						,      lowerCamelCase__=None   ):


      """simple docstring"""
      A__											=							1
      A__											=							self.hash_function(lowerCamelCase__   )

      while self.values[new_key] is not None and self.values[new_key] != key:
        A__											=							(
            self.__hash_double_function(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__   )
            if self.balanced_factor() >= self.lim_charge
            else None
        )
        if new_key is None:
          break
        else:
          i += 1

      return new_key




