
'''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 							snake_case				(		UpperCAmelCase						)->      CheckpointState:







      """simple docstring"""
      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	:Union[str, Any]						,					_A	:Path      )					->      Tuple:







       '''simple docstring'''



       __A													=      src_file






 def 						lowercase_    (      self	:Optional[int]      )					->      Optional[int]:







       '''simple docstring'''



       raise NotImplementedError






 @staticmethod
 def 						lowercase_    (      _A	:str						,					*_A	:Union[str, Any]						,					**_A	:Optional[int]      )					->      "DPRState":







       '''simple docstring'''



       if comp_type.startswith('c'      ):
             return DPRContextEncoderState(*_A						,					**_A      )
       if comp_type.startswith('q'      ):
             return DPRQuestionEncoderState(*_A						,					**_A      )
       if comp_type.startswith('r'      ):
             return DPRReaderState(*_A						,					**_A      )
       else:
             raise ValueError('Component type must be either \'ctx_encoder\', \'question_encoder\' or \'reader\'.'      )


class 			UpperCamelCase__	(     SCREAMING_SNAKE_CASE):






 def 						lowercase_    (      self	:List[Any]      )					->      Tuple:







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


class 			UpperCamelCase__	(     SCREAMING_SNAKE_CASE):






 def 						lowercase_    (      self	:Dict      )					->      str:







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


class 			UpperCamelCase__	(     SCREAMING_SNAKE_CASE):






 def 						lowercase_    (      self	:Tuple      )					->      Dict:







       '''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(_A      )
       return model





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase   ,	UpperCAmelCase						)->      List[Any]:







      """simple docstring"""
      __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__":
 a__		: Union[str, Any]  							=							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__		: List[str]  							=							parser.parse_args()

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





class 			UpperCamelCase__	:






 def __init__(      self	:Optional[Any]						,					_A	:Tuple      )					->      Tuple:







       '''simple docstring'''



       __A													=      data
       __A													=      None
       __A													=      None






 def __str__(      self	:List[str]      )					->      Optional[int]:







       '''simple docstring'''



       return F'{self.data}'


class 			UpperCamelCase__	:






 def __init__(      self	:List[Any]      )					->      Any:







       '''simple docstring'''



       __A													=      None
       __A													=      None






 def __iter__(      self	:Optional[int]      )					->      List[Any]:







       '''simple docstring'''



       __A													=      self.head
       while node:
             yield node.data
             __A													=      node.next






 def __str__(      self	:Dict      )					->      Union[str, Any]:







       '''simple docstring'''



       return "->".join([str(_A      ) for item in self]      )






 def __len__(      self	:int      )					->      List[str]:







       '''simple docstring'''



       return sum(1 for _ in self      )






 def 						lowercase_    (      self	:List[str]						,					_A	:Any      )					->      str:







       '''simple docstring'''



       self.insert_at_nth(0						,					_A      )






 def 						lowercase_    (      self	:Dict						,					_A	:Optional[Any]      )					->      Tuple:







       '''simple docstring'''



       self.insert_at_nth(len(self      )						,					_A      )






 def 						lowercase_    (      self	:Optional[int]						,					_A	:int						,					_A	:Optional[int]      )					->      int:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length:
             raise IndexError('list index out of range'      )
       __A													=      Node(_A      )
       if self.head is None:
             __A													=      __A													=      new_node
       elif index == 0:
             __A													=      new_node
             __A													=      self.head
             __A													=      new_node
       elif index == length:
             __A													=      new_node
             __A													=      self.tail
             __A													=      new_node
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      new_node
             __A													=      temp.previous
             __A													=      temp
             __A													=      new_node






 def 						lowercase_    (      self	:Optional[int]      )					->      List[str]:







       '''simple docstring'''



       return self.delete_at_nth(0      )






 def 						lowercase_    (      self	:Any      )					->      Tuple:







       '''simple docstring'''



       return self.delete_at_nth(len(self      ) - 1      )






 def 						lowercase_    (      self	:Dict						,					_A	:int      )					->      List[str]:







       '''simple docstring'''



       __A													=      len(self      )

       if not 0 <= index <= length - 1:
             raise IndexError('list index out of range'      )
       __A													=      self.head  # default first node
       if length == 1:
             __A													=      __A													=      None
       elif index == 0:
             __A													=      self.head.next
             __A													=      None
       elif index == length - 1:
             __A													=      self.tail
             __A													=      self.tail.previous
             __A													=      None
       else:
             __A													=      self.head
             for _ in range(0						,					_A      ):
                   __A													=      temp.next
             __A													=      temp
             __A													=      temp.previous
             __A													=      temp.next
       return delete_node.data






 def 						lowercase_    (      self	:List[str]						,					_A	:Dict      )					->      str:







       '''simple docstring'''



       __A													=      self.head

       while current.data != data:  # Find the position to delete
             if current.next:
                   __A													=      current.next
             else:  # We have reached the end an no value matches
                   raise ValueError('No data matching given value'      )

       if current == self.head:
             self.delete_head()

       elif current == self.tail:
             self.delete_tail()

       else:  # Before: 1 <--> 2(current) <--> 3
             __A													=      current.next  # 1 --> 3
             __A													=      current.previous  # 1 <--> 3
       return data






 def 						lowercase_    (      self	:List[str]      )					->      Tuple:







       '''simple docstring'''



       return len(self      ) == 0





def 							snake_case				(		)->      None:







      """simple docstring"""
      __A													=      DoublyLinkedList()
      assert linked_list.is_empty() is True
      assert str(UpperCAmelCase						) == ""

      try:
            linked_list.delete_head()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      try:
            linked_list.delete_tail()
            raise AssertionError  # This should not happen.
      except IndexError:
            assert True  # This should happen.

      for i in range(1_0						):
            assert len(UpperCAmelCase						) == i
            linked_list.insert_at_nth(UpperCAmelCase   ,	i + 1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_1						)						)

      linked_list.insert_at_head(0						)
      linked_list.insert_at_tail(1_1						)
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(0   ,	1_2						)						)

      assert linked_list.delete_head() == 0
      assert linked_list.delete_at_nth(9						) == 1_0
      assert linked_list.delete_tail() == 1_1
      assert len(UpperCAmelCase						) == 9
      assert str(UpperCAmelCase						) == "->".join(str(UpperCAmelCase						) for i in range(1   ,	1_0						)						)


if __name__ == "__main__":
 from doctest import testmod

 testmod()






