





'''simple docstring'''







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


snake_case_  :							int            =	logging.get_logger(__name__)

snake_case_  :							List[Any]            =	{
    "google/electra-small-generator": "https://huggingface.co/google/electra-small-generator/resolve/main/config.json",
    "google/electra-base-generator": "https://huggingface.co/google/electra-base-generator/resolve/main/config.json",
    "google/electra-large-generator": "https://huggingface.co/google/electra-large-generator/resolve/main/config.json",
    "google/electra-small-discriminator": (
        "https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json"
    ),
    "google/electra-base-discriminator": (
        "https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json"
    ),
    "google/electra-large-discriminator": (
        "https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json"
    ),
}


class        __a   (lowerCamelCase  ):
							__a       : str          =							"electra"

							def __init__(				self				:  List[Any]							,  __magic_name__				:  Optional[Any]=3_05_22							,  __magic_name__				:  int=1_28							,  __magic_name__				:  List[str]=2_56							,  __magic_name__				:  Union[str, Any]=12							,  __magic_name__				:  int=4							,  __magic_name__				:  Union[str, Any]=10_24							,  __magic_name__				:  str="gelu"							,  __magic_name__				:  int=0.1							,  __magic_name__				:  List[Any]=0.1							,  __magic_name__				:  Tuple=5_12							,  __magic_name__				:  Any=2							,  __magic_name__				:  List[str]=0.0_2							,  __magic_name__				:  int=1E-12							,  __magic_name__				:  Dict="first"							,  __magic_name__				:  List[Any]=True							,  __magic_name__				:  Tuple="gelu"							,  __magic_name__				:  Optional[Any]=0.1							,  __magic_name__				:  Dict=0							,  __magic_name__				:  List[str]="absolute"							,  __magic_name__				:  Tuple=True							,  __magic_name__				:  Optional[int]=None							,  **__magic_name__				:  Any							,  )       ->							List[Any]:







													"""simple docstring"""
													super().__init__(pad_token_id=__magic_name__							,  **__magic_name__ )

													UpperCAmelCase_      :   List[str]      =	vocab_size
													UpperCAmelCase_      :   int      =	embedding_size
													UpperCAmelCase_      :   List[str]      =	hidden_size
													UpperCAmelCase_      :   Any      =	num_hidden_layers
													UpperCAmelCase_      :   str      =	num_attention_heads
													UpperCAmelCase_      :   List[Any]      =	intermediate_size
													UpperCAmelCase_      :   Any      =	hidden_act
													UpperCAmelCase_      :   List[Any]      =	hidden_dropout_prob
													UpperCAmelCase_      :   Optional[Any]      =	attention_probs_dropout_prob
													UpperCAmelCase_      :   Optional[int]      =	max_position_embeddings
													UpperCAmelCase_      :   Union[str, Any]      =	type_vocab_size
													UpperCAmelCase_      :   Dict      =	initializer_range
													UpperCAmelCase_      :   int      =	layer_norm_eps

													UpperCAmelCase_      :   Dict      =	summary_type
													UpperCAmelCase_      :   Optional[int]      =	summary_use_proj
													UpperCAmelCase_      :   Optional[int]      =	summary_activation
													UpperCAmelCase_      :   Any      =	summary_last_dropout
													UpperCAmelCase_      :   List[Any]      =	position_embedding_type
													UpperCAmelCase_      :   Tuple      =	use_cache
													UpperCAmelCase_      :   int      =	classifier_dropout





class        __a   (lowerCamelCase  ):

							@property
							def      UpperCAmelCase__						(				self				:  Union[str, Any] )       ->							Mapping[str, Mapping[int, str]]:







													"""simple docstring"""
													if self.task == "multiple-choice":
																			UpperCAmelCase_      :   str      =	{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
													else:
																			UpperCAmelCase_      :   str      =	{0: '''batch''', 1: '''sequence'''}
													return OrderedDict(
													    [
													        ('''input_ids''', dynamic_axis),
													        ('''attention_mask''', dynamic_axis),
													        ('''token_type_ids''', dynamic_axis),
													    ] )






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 				UpperCamelCase					(     lowerCAmelCase_ )		->    CheckpointState:




       '''simple docstring'''






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





class   lowerCAmelCase    :



     def __init__(       self					,   lowerCAmelCase__							):
            _A=						src_file



     def       a__	(       self							):
            raise NotImplementedError





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





class   lowerCAmelCase    (       _a      ):



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





class   lowerCAmelCase    (       _a      ):



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





class   lowerCAmelCase    (       _a      ):



     def       a__	(       self							):
            _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(lowerCAmelCase__							)
            return model


def 				UpperCamelCase					(     lowerCAmelCase_							,       lowerCAmelCase_							,       lowerCAmelCase_ )		->    Tuple:




       '''simple docstring'''






       _A=						Path(lowerCAmelCase_ )
       dest_dir.mkdir(exist_ok=lowerCAmelCase_ )

       _A=						DPRState.from_type(lowerCAmelCase_							,       src_file=lowerCAmelCase_ )
       _A=						dpr_state.load_dpr_model()
       model.save_pretrained(lowerCAmelCase_ )
       model.from_pretrained(lowerCAmelCase_ )  # 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)