


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


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




def       _a      (		_lowercase   :      str    ):





     '''simple docstring'''






     print(F'Reading saved model from {model_file}'    )
     __UpperCAmelCase      :					Optional[int]    				=     torch.load(_lowercase     ,   map_location=lambda _lowercase     ,   _lowercase    : default_restore_location(_lowercase     ,   '''cpu'''    )    )
     return CheckpointState(**_lowercase    )



class       a							:


     """simple docstring"""






     def __init__(							self	:						List[str]				,					snake_case	:						Path     )		->				Union[str, Any]:
          __UpperCAmelCase      :					Any    				=     src_file

     def 					lowerCamelCase__					(							self	:						str     )		->				str:
          raise NotImplementedError






     @staticmethod
     def 					lowerCamelCase__					(							snake_case	:						str				,					*snake_case	:						Union[str, Any]				,					**snake_case	:						List[str]     )		->				"DPRState":
          if comp_type.startswith('''c'''     ):
               return DPRContextEncoderState(*snake_case				,					**snake_case     )
          if comp_type.startswith('''q'''     ):
               return DPRQuestionEncoderState(*snake_case				,					**snake_case     )
          if comp_type.startswith('''r'''     ):
               return DPRReaderState(*snake_case				,					**snake_case     )
          else:
               raise ValueError('''Component type must be either \'ctx_encoder\', \'question_encoder\' or \'reader\'.'''     )



class       a							(						_a			):


     """simple docstring"""






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



class       a							(						_a			):


     """simple docstring"""






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



class       a							(						_a			):


     """simple docstring"""






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




def       _a      (		_lowercase   :      str     ,   _lowercase   :      Path     ,   _lowercase   :      Path    ):





     '''simple docstring'''






     __UpperCAmelCase      :					Optional[Any]    				=     Path(_lowercase    )
     dest_dir.mkdir(exist_ok=_lowercase    )

     __UpperCAmelCase      :					List[str]    				=     DPRState.from_type(_lowercase     ,   src_file=_lowercase    )
     __UpperCAmelCase      :					Tuple    				=     dpr_state.load_dpr_model()
     model.save_pretrained(_lowercase    )
     model.from_pretrained(_lowercase    )  # sanity check


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

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



import unittest
import warnings
from dataclasses import dataclass

from transformers.convert_slow_tokenizer import SpmConverter
from transformers.testing_utils import get_tests_dir



@dataclass
class       a							:


     """simple docstring"""






     SCREAMING_SNAKE_CASE			:					str



class       a							(						unittest.TestCase			):


     """simple docstring"""






     def 					lowerCamelCase__					(							self	:						str     )		->				Dict:
          __UpperCAmelCase      :					str    				=     get_tests_dir('''fixtures/test_sentencepiece.model'''     )
          __UpperCAmelCase      :					List[Any]    				=     get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model'''     )

          __UpperCAmelCase      :					Tuple    				=     FakeOriginalTokenizer(vocab_file=snake_case     )

          with warnings.catch_warnings(record=snake_case     ) as w:
               __UpperCAmelCase      :					Optional[int]    				=     SpmConverter(snake_case     )
          self.assertEqual(len(snake_case     )				,					0     )

          __UpperCAmelCase      :					str    				=     FakeOriginalTokenizer(vocab_file=snake_case     )

          with warnings.catch_warnings(record=snake_case     ) as w:
               __UpperCAmelCase      :					Optional[int]    				=     SpmConverter(snake_case     )
          self.assertEqual(len(snake_case     )				,					1     )

          self.assertIn(
              '''The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option'''
              ''' which is not implemented in the fast tokenizers.'''				,					str(w[0].message     )				,					)