





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


a__       :  int       		=					collections.namedtuple(
    """CheckpointState""", ["""model_dict""", """optimizer_dict""", """scheduler_dict""", """offset""", """epoch""", """encoder_params"""]
)





def 				a__      (	_UpperCAmelCase						)     ->	CheckpointState:

 '''simple docstring'''






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



class   lowercase_					:

       def __init__(      self ,       __SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					src_file

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

        raise NotImplementedError

       @staticmethod
       def 		_SCREAMING_SNAKE_CASE(      __SCREAMING_SNAKE_CASE ,       *__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        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   lowercase_					(  __lowerCAmelCase				):

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

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



class   lowercase_					(  __lowerCAmelCase				):

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

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



class   lowercase_					(  __lowerCAmelCase				):

       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

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





def 				a__      (	_UpperCAmelCase						,  _UpperCAmelCase						,  _UpperCAmelCase						)     ->	List[str]:

 '''simple docstring'''






 snake_case__     				=					Path(_UpperCAmelCase						)
 dest_dir.mkdir(exist_ok=_UpperCAmelCase						)

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


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

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


def 				a__      (	_UpperCAmelCase						,  _UpperCAmelCase						,  _UpperCAmelCase						)     ->	float:

 '''simple docstring'''






 snake_case__     				=					[1 / first_term]
 snake_case__     				=					1 / first_term
 for _ in range(number_of_terms - 1						):
  first_term += common_difference
  arithmetic_progression.append(_UpperCAmelCase						)
 snake_case__     				=					[1 / step for step in arithmetic_progression]
 return sum(_UpperCAmelCase						)


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   print(sum_of_harmonic_progression(1 / 2, 2, 2))

