




'''simple docstring'''







from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


A			   =logging.get_logger(__name__)

A			   ={
    'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
    'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
    'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
    'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
    'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
}


class       _a  (     __a			):
       __a    :					Union[str, Any]           = """gpt2"""
       __a    :					Any           = ["""past_key_values"""]
       __a    :					Tuple           = {
           """hidden_size""": """n_embd""",
           """max_position_embeddings""": """n_positions""",
           """num_attention_heads""": """n_head""",
           """num_hidden_layers""": """n_layer""",
       }
       def __init__(     self						:     Tuple       ,    lowercase						:     Dict=50_257       ,    lowercase						:     Any=1_024       ,    lowercase						:     Any=768       ,    lowercase						:     Any=12       ,    lowercase						:     Union[str, Any]=12       ,    lowercase						:     int=None       ,    lowercase						:     int="gelu_new"       ,    lowercase						:     str=0.1       ,    lowercase						:     Any=0.1       ,    lowercase						:     List[str]=0.1       ,    lowercase						:     List[Any]=1E-5       ,    lowercase						:     List[Any]=0.02       ,    lowercase						:     int="cls_index"       ,    lowercase						:     Optional[Any]=True       ,    lowercase						:     str=None       ,    lowercase						:     Union[str, Any]=True       ,    lowercase						:     List[Any]=0.1       ,    lowercase						:     Optional[int]=True       ,    lowercase						:     int=True       ,    lowercase						:     Optional[Any]=50_256       ,    lowercase						:     Dict=50_256       ,    lowercase						:     str=False       ,    lowercase						:     str=False       ,    **lowercase						:     int       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		vocab_size
           UpperCAmelCase      	=		n_positions
           UpperCAmelCase      	=		n_embd
           UpperCAmelCase      	=		n_layer
           UpperCAmelCase      	=		n_head
           UpperCAmelCase      	=		n_inner
           UpperCAmelCase      	=		activation_function
           UpperCAmelCase      	=		resid_pdrop
           UpperCAmelCase      	=		embd_pdrop
           UpperCAmelCase      	=		attn_pdrop
           UpperCAmelCase      	=		layer_norm_epsilon
           UpperCAmelCase      	=		initializer_range
           UpperCAmelCase      	=		summary_type
           UpperCAmelCase      	=		summary_use_proj
           UpperCAmelCase      	=		summary_activation
           UpperCAmelCase      	=		summary_first_dropout
           UpperCAmelCase      	=		summary_proj_to_labels
           UpperCAmelCase      	=		scale_attn_weights
           UpperCAmelCase      	=		use_cache
           UpperCAmelCase      	=		scale_attn_by_inverse_layer_idx
           UpperCAmelCase      	=		reorder_and_upcast_attn

           UpperCAmelCase      	=		bos_token_id
           UpperCAmelCase      	=		eos_token_id

           super().__init__(bos_token_id=lowercase       ,    eos_token_id=lowercase       ,    **lowercase    )






class       _a  (     __a			):
       def __init__(     self						:     Optional[int]       ,    lowercase						:     PretrainedConfig       ,    lowercase						:     str = "default"       ,    lowercase						:     List[PatchingSpec] = None       ,    lowercase						:     bool = False       ,    ):



           '''simple docstring'''

           super().__init__(lowercase       ,    task=lowercase       ,    patching_specs=lowercase       ,    use_past=lowercase    )
           if not getattr(self._config       ,    '''pad_token_id'''       ,    lowercase    ):
               # TODO: how to do that better?
               UpperCAmelCase      	=		0
       @property
       def    A				(     self						:     Dict    ):



           '''simple docstring'''

           UpperCAmelCase      	=		OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}    )
           if self.use_past:
               self.fill_with_past_key_values_(lowercase       ,    direction='''inputs'''    )
               UpperCAmelCase      	=		{0: '''batch''', 1: '''past_sequence + sequence'''}
           else:
               UpperCAmelCase      	=		{0: '''batch''', 1: '''sequence'''}

           return common_inputs
       @property
       def    A				(     self						:     Optional[int]    ):



           '''simple docstring'''

           return self._config.n_layer
       @property
       def    A				(     self						:     str    ):



           '''simple docstring'''

           return self._config.n_head
       def    A				(     self						:     Optional[Any]       ,    lowercase						:     PreTrainedTokenizer       ,    lowercase						:     int = -1       ,    lowercase						:     int = -1       ,    lowercase						:     bool = False       ,    lowercase						:     Optional[TensorType] = None       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		super(lowercase       ,    self    ).generate_dummy_inputs(
               lowercase       ,    batch_size=lowercase       ,    seq_length=lowercase       ,    is_pair=lowercase       ,    framework=lowercase    )

           # We need to order the input in the way they appears in the forward()
           UpperCAmelCase      	=		OrderedDict({'''input_ids''': common_inputs['''input_ids''']}    )

           # Need to add the past_keys
           if self.use_past:
               if not is_torch_available():
                   raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''    )
               else:
                   import torch

                   UpperCAmelCase	,					UpperCAmelCase      	=		common_inputs['''input_ids'''].shape
                   # Not using the same length for past_key_values
                   UpperCAmelCase      	=		seqlen + 2
                   UpperCAmelCase      	=		(
                       batch,
                       self.num_attention_heads,
                       past_key_values_length,
                       self._config.hidden_size // self.num_attention_heads,
                   )
                   UpperCAmelCase      	=		[
                       (torch.zeros(lowercase    ), torch.zeros(lowercase    )) for _ in range(self.num_layers    )
                   ]

           UpperCAmelCase      	=		common_inputs['''attention_mask''']
           if self.use_past:
               UpperCAmelCase      	=		ordered_inputs['''attention_mask'''].dtype
               UpperCAmelCase      	=		torch.cat(
                   [ordered_inputs['''attention_mask'''], torch.ones(lowercase       ,    lowercase       ,    dtype=lowercase    )]       ,    dim=1    )

           return ordered_inputs







       @property
       def    A				(     self						:     str    ):



           '''simple docstring'''

           return 13










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





def 						snake_case_							(_a     :							str					):
    print(F"Reading saved model from {model_file}"					)
    UpperCAmelCase      	=		torch.load(_a   ,       map_location=lambda _a   ,       _a					: default_restore_location(_a   ,       '''cpu'''					)					)
    return CheckpointState(**_a					)


class       _a  :
       def __init__(     self						:     List[Any]       ,    lowercase						:     Path    ):



           '''simple docstring'''

           UpperCAmelCase      	=		src_file
       def    A				(     self						:     str    ):



           '''simple docstring'''

           raise NotImplementedError







       @staticmethod
       def    A				(     lowercase						:     str       ,    *lowercase						:     Tuple       ,    **lowercase						:     Union[str, Any]    ):



           '''simple docstring'''

           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       _a  (     __a			):
       def    A				(     self						:     int    ):



           '''simple docstring'''

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






class       _a  (     __a			):
       def    A				(     self						:     int    ):



           '''simple docstring'''

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






class       _a  (     __a			):
       def    A				(     self						:     int    ):



           '''simple docstring'''

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






def 						snake_case_							(_a     :							str   ,       _a     :							Path   ,       _a     :							Path					):
    UpperCAmelCase      	=		Path(_a					)
    dest_dir.mkdir(exist_ok=_a					)

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


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

   A			   =Path(args.src)
   A			   =f"""converted-{src_file.name}""" if args.dest is None else args.dest
   A			   =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)




