




'''simple docstring'''







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

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


A			   =logging.get_logger(__name__)

A			   ={
    'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json',
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}


class       _a  (     __a			):
       __a    :					List[Any]           = """blenderbot"""
       __a    :					Optional[int]           = ["""past_key_values"""]
       __a    :					Any           = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}
       def __init__(     self						:     Optional[int]       ,    lowercase						:     List[Any]=8_008       ,    lowercase						:     Tuple=128       ,    lowercase						:     str=2       ,    lowercase						:     str=10_240       ,    lowercase						:     Optional[int]=32       ,    lowercase						:     Dict=24       ,    lowercase						:     Optional[Any]=10_240       ,    lowercase						:     List[str]=32       ,    lowercase						:     Optional[Any]=0.0       ,    lowercase						:     Any=0.0       ,    lowercase						:     int=True       ,    lowercase						:     Any=True       ,    lowercase						:     int="gelu"       ,    lowercase						:     str=2_560       ,    lowercase						:     Union[str, Any]=0.1       ,    lowercase						:     Optional[int]=0.0       ,    lowercase						:     Optional[Any]=0.0       ,    lowercase						:     int=0.02       ,    lowercase						:     Tuple=1       ,    lowercase						:     List[str]=False       ,    lowercase						:     Optional[int]=0       ,    lowercase						:     Optional[int]=1       ,    lowercase						:     Any=2       ,    lowercase						:     Tuple=3       ,    lowercase						:     Any=2       ,    **lowercase						:     Any       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		vocab_size
           UpperCAmelCase      	=		max_position_embeddings
           UpperCAmelCase      	=		d_model
           UpperCAmelCase      	=		encoder_ffn_dim
           UpperCAmelCase      	=		encoder_layers
           UpperCAmelCase      	=		encoder_attention_heads
           UpperCAmelCase      	=		decoder_ffn_dim
           UpperCAmelCase      	=		decoder_layers
           UpperCAmelCase      	=		decoder_attention_heads
           UpperCAmelCase      	=		dropout
           UpperCAmelCase      	=		attention_dropout
           UpperCAmelCase      	=		activation_dropout
           UpperCAmelCase      	=		activation_function
           UpperCAmelCase      	=		init_std
           UpperCAmelCase      	=		encoder_layerdrop
           UpperCAmelCase      	=		decoder_layerdrop
           UpperCAmelCase      	=		use_cache
           UpperCAmelCase      	=		encoder_layers
           UpperCAmelCase      	=		scale_embedding  # scale factor will be sqrt(d_model) if True

           super().__init__(
               pad_token_id=lowercase       ,    bos_token_id=lowercase       ,    eos_token_id=lowercase       ,    is_encoder_decoder=lowercase       ,    decoder_start_token_id=lowercase       ,    encoder_no_repeat_ngram_size=lowercase       ,    forced_eos_token_id=lowercase       ,    **lowercase       ,    )






class       _a  (     __a			):
       @property
       def    A				(     self						:     str    ):



           '''simple docstring'''

           if self.task in ["default", "seq2seq-lm"]:
               UpperCAmelCase      	=		OrderedDict(
                   [
                       ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                       ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
                   ]    )
               if self.use_past:
                   UpperCAmelCase      	=		{0: '''batch'''}
                   UpperCAmelCase      	=		{0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
               else:
                   UpperCAmelCase      	=		{0: '''batch''', 1: '''decoder_sequence'''}
                   UpperCAmelCase      	=		{0: '''batch''', 1: '''decoder_sequence'''}
               if self.use_past:
                   self.fill_with_past_key_values_(lowercase       ,    direction='''inputs'''    )
           elif self.task == "causal-lm":
               UpperCAmelCase      	=		OrderedDict(
                   [
                       ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                       ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
                   ]    )
               if self.use_past:
                   UpperCAmelCase	,					UpperCAmelCase      	=		self.num_layers
                   for i in range(lowercase    ):
                       UpperCAmelCase      	=		{0: '''batch''', 2: '''past_sequence + sequence'''}
                       UpperCAmelCase      	=		{0: '''batch''', 2: '''past_sequence + sequence'''}
           else:
               UpperCAmelCase      	=		OrderedDict(
                   [
                       ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                       ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
                       ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
                       ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
                   ]    )

           return common_inputs
       @property
       # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
       def    A				(     self						:     Optional[Any]    ):



           '''simple docstring'''

           if self.task in ["default", "seq2seq-lm"]:
               UpperCAmelCase      	=		super().outputs
           else:
               UpperCAmelCase      	=		super(lowercase       ,    self    ).outputs
               if self.use_past:
                   UpperCAmelCase	,					UpperCAmelCase      	=		self.num_layers
                   for i in range(lowercase    ):
                       UpperCAmelCase      	=		{0: '''batch''', 2: '''past_sequence + sequence'''}
                       UpperCAmelCase      	=		{0: '''batch''', 2: '''past_sequence + sequence'''}
           return common_outputs
       def    A				(     self						:     Union[str, Any]       ,    lowercase						:     PreTrainedTokenizer       ,    lowercase						:     int = -1       ,    lowercase						:     int = -1       ,    lowercase						:     bool = False       ,    lowercase						:     Optional[TensorType] = None       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
               lowercase       ,    lowercase       ,    lowercase       ,    lowercase       ,    lowercase    )
           # Generate decoder inputs
           UpperCAmelCase      	=		seq_length if not self.use_past else 1
           UpperCAmelCase      	=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
               lowercase       ,    lowercase       ,    lowercase       ,    lowercase       ,    lowercase    )
           UpperCAmelCase      	=		{f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
           UpperCAmelCase      	=		dict(**lowercase       ,    **lowercase    )

           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
               UpperCAmelCase      	=		common_inputs['''decoder_input_ids'''].shape[1]
               UpperCAmelCase	,					UpperCAmelCase      	=		self.num_attention_heads
               UpperCAmelCase      	=		(
                   batch,
                   num_encoder_attention_heads,
                   encoder_seq_length,
                   self._config.hidden_size // num_encoder_attention_heads,
               )
               UpperCAmelCase      	=		decoder_seq_length
               UpperCAmelCase      	=		(
                   batch,
                   num_decoder_attention_heads,
                   decoder_past_length,
                   self._config.hidden_size // num_decoder_attention_heads,
               )
               UpperCAmelCase      	=		torch.cat(
                   [common_inputs['''decoder_attention_mask'''], torch.ones(lowercase       ,    lowercase    )]       ,    dim=1    )
               UpperCAmelCase      	=		[]
               UpperCAmelCase	,					UpperCAmelCase      	=		self.num_layers

               for _ in range(lowercase    ):
                   common_inputs["past_key_values"].append(
                       (
                           torch.zeros(lowercase    ),
                           torch.zeros(lowercase    ),
                           torch.zeros(lowercase    ),
                           torch.zeros(lowercase    ),
                       )    )
           return common_inputs
       def    A				(     self						:     Optional[int]       ,    lowercase						:     PreTrainedTokenizer       ,    lowercase						:     int = -1       ,    lowercase						:     int = -1       ,    lowercase						:     bool = False       ,    lowercase						:     Optional[TensorType] = None       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
               lowercase       ,    lowercase       ,    lowercase       ,    lowercase       ,    lowercase    )

           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
               UpperCAmelCase      	=		seqlen
               UpperCAmelCase	,					UpperCAmelCase      	=		self.num_layers
               UpperCAmelCase	,					UpperCAmelCase      	=		self.num_attention_heads
               UpperCAmelCase      	=		(
                   batch,
                   num_encoder_attention_heads,
                   past_key_values_length,
                   self._config.hidden_size // num_encoder_attention_heads,
               )
               UpperCAmelCase      	=		common_inputs['''attention_mask'''].dtype
               UpperCAmelCase      	=		torch.cat(
                   [common_inputs['''attention_mask'''], torch.ones(lowercase       ,    lowercase       ,    dtype=lowercase    )]       ,    dim=1    )
               UpperCAmelCase      	=		[
                   (torch.zeros(lowercase    ), torch.zeros(lowercase    )) for _ in range(lowercase    )
               ]
           return common_inputs
       def    A				(     self						:     List[str]       ,    lowercase						:     PreTrainedTokenizer       ,    lowercase						:     int = -1       ,    lowercase						:     int = -1       ,    lowercase						:     bool = False       ,    lowercase						:     Optional[TensorType] = None       ,    ):



           '''simple docstring'''

           UpperCAmelCase      	=		compute_effective_axis_dimension(
               lowercase       ,    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
           UpperCAmelCase      	=		tokenizer.num_special_tokens_to_add(lowercase    )
           UpperCAmelCase      	=		compute_effective_axis_dimension(
               lowercase       ,    fixed_dimension=OnnxConfig.default_fixed_sequence       ,    num_token_to_add=lowercase    )

           # Generate dummy inputs according to compute batch and sequence
           UpperCAmelCase      	=		[''' '''.join([tokenizer.unk_token]    ) * seq_length] * batch_size
           UpperCAmelCase      	=		dict(tokenizer(lowercase       ,    return_tensors=lowercase    )    )
           return common_inputs
       def    A				(     self						:     int       ,    lowercase						:     PreTrainedTokenizer       ,    lowercase						:     int = -1       ,    lowercase						:     int = -1       ,    lowercase						:     bool = False       ,    lowercase						:     Optional[TensorType] = None       ,    ):



           '''simple docstring'''

           if self.task in ["default", "seq2seq-lm"]:
               UpperCAmelCase      	=		self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                   lowercase       ,    batch_size=lowercase       ,    seq_length=lowercase       ,    is_pair=lowercase       ,    framework=lowercase    )

           elif self.task == "causal-lm":
               UpperCAmelCase      	=		self._generate_dummy_inputs_for_causal_lm(
                   lowercase       ,    batch_size=lowercase       ,    seq_length=lowercase       ,    is_pair=lowercase       ,    framework=lowercase    )
           else:
               UpperCAmelCase      	=		self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                   lowercase       ,    batch_size=lowercase       ,    seq_length=lowercase       ,    is_pair=lowercase       ,    framework=lowercase    )

           return common_inputs
       def    A				(     self						:     List[str]       ,    lowercase						:     List[Any]       ,    lowercase						:     Optional[Any]       ,    lowercase						:     Optional[Any]       ,    lowercase						:     Tuple    ):



           '''simple docstring'''

           if self.task in ["default", "seq2seq-lm"]:
               UpperCAmelCase      	=		super()._flatten_past_key_values_(lowercase       ,    lowercase       ,    lowercase       ,    lowercase    )
           else:
               UpperCAmelCase      	=		super(lowercase       ,    self    )._flatten_past_key_values_(
                   lowercase       ,    lowercase       ,    lowercase       ,    lowercase    )







       def    A				(     self						:     Optional[Any]       ,    lowercase						:     Mapping[str, Mapping[int, str]]       ,    lowercase						:     str    ):



           '''simple docstring'''

           if direction not in ["inputs", "outputs"]:
               raise ValueError(f"direction must either be \"inputs\" or \"outputs\", but {direction} was given"    )

           UpperCAmelCase      	=		'''past_key_values''' if direction == '''inputs''' else '''present'''
           UpperCAmelCase	,					UpperCAmelCase      	=		self.num_layers

           UpperCAmelCase      	=		'''past_encoder_sequence'''
           UpperCAmelCase      	=		'''past_decoder_sequence''' if direction == '''inputs''' else '''past_decoder_sequence + sequence'''

           for i in range(lowercase    ):
               UpperCAmelCase      	=		{0: '''batch''', 2: decoder_sequence}
               UpperCAmelCase      	=		{0: '''batch''', 2: decoder_sequence}
               UpperCAmelCase      	=		{0: '''batch''', 2: encoder_sequence}
               UpperCAmelCase      	=		{0: '''batch''', 2: encoder_sequence}










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




