code: 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
  
  
  _SCREAMING_SNAKE_CASE   						=    collections.namedtuple(
      """CheckpointState""", ["""model_dict""", """optimizer_dict""", """scheduler_dict""", """offset""", """epoch""", """encoder_params"""]
  )
  def 				__lowercase	(						lowerCamelCase__					)				->Any:
  
    '''simple docstring'''
  
  
  
  
    print(f"Reading saved model from {model_file}"					)
    a__     		=     torch.load(_A ,				map_location=lambda lowerCamelCase__ ,				lowerCamelCase__					: default_restore_location(_A ,				"cpu"					)					)
    return CheckpointState(**_A					)
  
  
  
  
  
  
  
  class 					UpperCAmelCase_				:
  
      '''simple docstring'''
  
  
  
  
  
      def __init__(					self  :   Union[str, Any]      ,      lowerCAmelCase  :   int   )	-> int:
        a__     		=     src_file
  
  
  
  
      def 						__lowerCamelCase (					self  :   List[str]   )	-> int:
        raise NotImplementedError
  
  
  
  
      @staticmethod
      def 						__lowerCamelCase (					lowerCAmelCase  :   Optional[int]      ,      *lowerCAmelCase  :   List[Any]      ,      **lowerCAmelCase  :   Union[str, Any]   )	-> "DPRState":
  
  
  
  
  
  
        if comp_type.startswith("c"   ):
          return DPRContextEncoderState(*lowercase_      ,      **lowercase_   )
        if comp_type.startswith("q"   ):
          return DPRQuestionEncoderState(*lowercase_      ,      **lowercase_   )
        if comp_type.startswith("r"   ):
          return DPRReaderState(*lowercase_      ,      **lowercase_   )
        else:
          raise ValueError("Component type must be either \'ctx_encoder\', \'question_encoder\' or \'reader\'."   )
  
  
  
  
  
  
  
  class 					UpperCAmelCase_				(							lowerCamelCase__    ):
  
      '''simple docstring'''
  
  
  
  
  
      def 						__lowerCamelCase (					self  :   Optional[Any]   )	-> Any:
        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(lowercase_   ):
            a__     		=     key[len(lowercase_   ) :]
            if not key.startswith("encode_proj."   ):
              a__     		=     "bert_model." + key
            a__     		=     value
        encoder.load_state_dict(lowercase_   )
        return model
  
  
  
  
  
  
  
  class 					UpperCAmelCase_				(							lowerCamelCase__    ):
  
      '''simple docstring'''
  
  
  
  
  
      def 						__lowerCamelCase (					self  :   List[str]   )	-> Tuple:
        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(lowercase_   ):
            a__     		=     key[len(lowercase_   ) :]
            if not key.startswith("encode_proj."   ):
              a__     		=     "bert_model." + key
            a__     		=     value
        encoder.load_state_dict(lowercase_   )
        return model
  
  
  
  
  
  
  
  class 					UpperCAmelCase_				(							lowerCamelCase__    ):
  
      '''simple docstring'''
  
  
  
  
  
      def 						__lowerCamelCase (					self  :   Union[str, Any]   )	-> Union[str, Any]:
        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(lowercase_   )
        return model
  
  def 				__lowercase	(						lowerCamelCase__ ,				lowerCamelCase__ ,				lowerCamelCase__					)				->int:
  
    '''simple docstring'''
  
  
  
  
    a__     		=     Path(_A					)
    dest_dir.mkdir(exist_ok=_A					)
  
    a__     		=     DPRState.from_type(_A ,				src_file=_A					)
    a__     		=     dpr_state.load_dpr_model()
    model.save_pretrained(_A					)
    model.from_pretrained(_A					)  # sanity check
  
  
  if __name__ == "__main__":
       _SCREAMING_SNAKE_CASE   						=    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.""")
       _SCREAMING_SNAKE_CASE   						=    parser.parse_args()
  
       _SCREAMING_SNAKE_CASE   						=    Path(args.src)
       _SCREAMING_SNAKE_CASE   						=    F"""converted-{src_file.name}""" if args.dest is None else args.dest
       _SCREAMING_SNAKE_CASE   						=    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)
  
  
style_context: from unittest.mock import patch
  
  import datasets
  from datasets import Dataset
  def 				__lowercase	(						)				->Union[str, Any]:
  
    '''simple docstring'''
  
  
  
  
    a__     		=     Dataset.from_dict({"col_1": [3, 2, 0, 1]}					)
  
    with patch("tqdm.auto.tqdm"					) as mock_tqdm:
      datasets.disable_progress_bar()
      dset.map(lambda lowerCamelCase__					: {"col_2": x["col_1"] + 1}					)
      mock_tqdm.assert_not_called()
  
      mock_tqdm.reset_mock()
  
      datasets.enable_progress_bar()
      dset.map(lambda lowerCamelCase__					: {"col_2": x["col_1"] + 1}					)
      mock_tqdm.assert_called()
  
  