






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




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase							):


   """simple docstring"""




   print(F"""Reading saved model from {model_file}"""							)
   lowercase_		:      Tuple          =       torch.load(_UpperCamelCase  ,						map_location=lambda _UpperCamelCase  ,						_UpperCamelCase							: default_restore_location(_UpperCamelCase  ,						"cpu"							)							)
   return CheckpointState(**_UpperCamelCase							)


class     _UpperCAmelCase  :




    def __init__(     self					:    int					,       a					:    Path     ):






       '''simple docstring'''






       lowercase_		:      str          =       src_file




    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






       raise NotImplementedError





    @staticmethod
    def 			lowerCAmelCase__			(     a					:    str					,       *a					:    Optional[int]					,       **a					:    List[str]     ):






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




    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






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


class     _UpperCAmelCase  (						snake_case     ):




    def 			lowerCAmelCase__			(     self					:    Optional[int]     ):






       '''simple docstring'''






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


class     _UpperCAmelCase  (						snake_case     ):




    def 			lowerCAmelCase__			(     self					:    Dict     ):






       '''simple docstring'''






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




def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase  ,						_UpperCamelCase  ,						_UpperCamelCase							):


   """simple docstring"""




   lowercase_		:      Optional[int]          =       Path(_UpperCamelCase							)
   dest_dir.mkdir(exist_ok=_UpperCamelCase							)

   lowercase_		:      List[Any]          =       DPRState.from_type(_UpperCamelCase  ,						src_file=_UpperCamelCase							)
   lowercase_		:      Any          =       dpr_state.load_dpr_model()
   model.save_pretrained(_UpperCamelCase							)
   model.from_pretrained(_UpperCamelCase							)  # sanity check


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

 UpperCamelCase__	=     Path(args.src)
 UpperCamelCase__	=     f"""converted-{src_file.name}""" if args.dest is None else args.dest
 UpperCamelCase__	=     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 collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


UpperCamelCase__	=     logging.get_logger(__name__)

UpperCamelCase__	=     {
    'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/config.json',
    # See all M2M100 models at https://huggingface.co/models?filter=m2m_100
}


class     _UpperCAmelCase  (						snake_case     ):
    __lowerCamelCase:				List[Any]						    =      'm2m_100'
    __lowerCamelCase:				Union[str, Any]						    =      ['past_key_values']
    __lowerCamelCase:				Union[str, Any]						    =      {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}




    def __init__(     self					:    str					,       a					:    Optional[Any]=1_2_8_1_1_2					,       a					:    Optional[int]=1_0_2_4					,       a					:    Any=1_2					,       a					:    Tuple=4_0_9_6					,       a					:    Any=1_6					,       a					:    Any=1_2					,       a					:    Dict=4_0_9_6					,       a					:    List[str]=1_6					,       a					:    List[Any]=0.05					,       a					:    Optional[int]=0.05					,       a					:    List[Any]=True					,       a					:    List[Any]=True					,       a					:    Union[str, Any]="relu"					,       a					:    Optional[Any]=1_0_2_4					,       a					:    List[str]=0.1					,       a					:    Union[str, Any]=0.1					,       a					:    int=0.0					,       a					:    List[str]=0.02					,       a					:    Optional[int]=2					,       a					:    Tuple=True					,       a					:    List[str]=1					,       a					:    int=0					,       a					:    int=2					,       **a					:    Tuple					,       ):






       '''simple docstring'''






       lowercase_		:      List[str]          =       vocab_size
       lowercase_		:      Tuple          =       max_position_embeddings
       lowercase_		:      int          =       d_model
       lowercase_		:      Optional[int]          =       encoder_ffn_dim
       lowercase_		:      Any          =       encoder_layers
       lowercase_		:      Optional[Any]          =       encoder_attention_heads
       lowercase_		:      List[Any]          =       decoder_ffn_dim
       lowercase_		:      Union[str, Any]          =       decoder_layers
       lowercase_		:      Optional[Any]          =       decoder_attention_heads
       lowercase_		:      Optional[int]          =       dropout
       lowercase_		:      Optional[Any]          =       attention_dropout
       lowercase_		:      Optional[int]          =       activation_dropout
       lowercase_		:      Any          =       activation_function
       lowercase_		:      Optional[Any]          =       init_std
       lowercase_		:      Tuple          =       encoder_layerdrop
       lowercase_		:      Optional[Any]          =       decoder_layerdrop
       lowercase_		:      List[Any]          =       use_cache
       lowercase_		:      Dict          =       encoder_layers
       lowercase_		:      Tuple          =       scale_embedding  # scale factor will be sqrt(d_model) if True

       super().__init__(
           pad_token_id=a					,       bos_token_id=a					,       eos_token_id=a					,       is_encoder_decoder=a					,       decoder_start_token_id=a					,       **a					,       )


class     _UpperCAmelCase  (						snake_case     ):




    @property
    def 			lowerCAmelCase__			(     self					:    Optional[Any]     ):






       '''simple docstring'''






       lowercase_		:      List[Any]          =       OrderedDict(
           [
               ("input_ids", {0: "batch", 1: "encoder_sequence"}),
               ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
           ]     )

       if self.use_past:
          lowercase_		:      Optional[int]          =       {0: "batch"}
          lowercase_		:      str          =       {0: "batch", 1: "past_decoder_sequence + sequence"}
       else:
          lowercase_		:      Optional[Any]          =       {0: "batch", 1: "decoder_sequence"}
          lowercase_		:      Union[str, Any]          =       {0: "batch", 1: "decoder_sequence"}

       if self.use_past:
          self.fill_with_past_key_values_(a					,       direction="inputs"     )
       return common_inputs




    def 			lowerCAmelCase__			(     self					:    Dict					,       a					:    PreTrainedTokenizer					,       a					:    int = -1					,       a					:    int = -1					,       a					:    bool = False					,       a					:    Optional[TensorType] = None					,       ):






       '''simple docstring'''






       lowercase_		:      int          =       compute_effective_axis_dimension(
           a					,       fixed_dimension=OnnxConfig.default_fixed_batch					,       num_token_to_add=0     )

       # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
       lowercase_		:      Dict          =       tokenizer.num_special_tokens_to_add(a     )
       lowercase_		:      str          =       compute_effective_axis_dimension(
           a					,       fixed_dimension=OnnxConfig.default_fixed_sequence					,       num_token_to_add=a     )

       # Generate dummy inputs according to compute batch and sequence
       lowercase_		:      Union[str, Any]          =       [" ".join([tokenizer.unk_token]     ) * seq_length] * batch_size
       lowercase_		:      Tuple          =       dict(tokenizer(a					,       return_tensors=a     )     )
       return common_inputs




    def 			lowerCAmelCase__			(     self					:    Any					,       a					:    PreTrainedTokenizer					,       a					:    int = -1					,       a					:    int = -1					,       a					:    bool = False					,       a					:    Optional[TensorType] = None					,       ):






       '''simple docstring'''






       lowercase_		:      Optional[Any]          =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           a					,       a					,       a					,       a					,       a     )

       # Generate decoder inputs
       lowercase_		:      List[str]          =       seq_length if not self.use_past else 1
       lowercase_		:      Dict          =       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           a					,       a					,       a					,       a					,       a     )
       lowercase_		:      Union[str, Any]          =       {f"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
       lowercase_		:      Union[str, Any]          =       dict(**a					,       **a     )

       if self.use_past:
          if not is_torch_available():
             raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."     )
          else:
             import torch
          lowercase_      ,						lowercase_		:      Union[str, Any]          =       common_inputs["input_ids"].shape
          lowercase_		:      List[Any]          =       common_inputs["decoder_input_ids"].shape[1]
          lowercase_      ,						lowercase_		:      Optional[Any]          =       self.num_attention_heads
          lowercase_		:      Any          =       (
              batch,
              num_encoder_attention_heads,
              encoder_seq_length,
              self._config.hidden_size // num_encoder_attention_heads,
          )
          lowercase_		:      Optional[Any]          =       decoder_seq_length + 3
          lowercase_		:      int          =       (
              batch,
              num_decoder_attention_heads,
              decoder_past_length,
              self._config.hidden_size // num_decoder_attention_heads,
          )

          lowercase_		:      Dict          =       torch.cat(
              [common_inputs["decoder_attention_mask"], torch.ones(a					,       a     )]					,       dim=1     )

          lowercase_		:      Tuple          =       []
          # If the number of encoder and decoder layers are present in the model configuration, both are considered
          lowercase_      ,						lowercase_		:      Tuple          =       self.num_layers
          lowercase_		:      Optional[Any]          =       min(a					,       a     )
          lowercase_		:      Tuple          =       max(a					,       a     ) - min_num_layers
          lowercase_		:      Optional[int]          =       "encoder" if num_encoder_layers > num_decoder_layers else "decoder"

          for _ in range(a     ):
             common_inputs["past_key_values"].append(
                 (
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                     torch.zeros(a     ),
                 )     )
          # TODO: test this.
          lowercase_		:      Union[str, Any]          =       encoder_shape if remaining_side_name == "encoder" else decoder_shape
          for _ in range(a					,       a     ):
             common_inputs["past_key_values"].append((torch.zeros(a     ), torch.zeros(a     ))     )
       return common_inputs





    __lowerCamelCase:				str						    =      _generate_dummy_inputs_for_default_and_seqaseq_lm




