





"""simple docstring"""





import json
import os
import shutil
import sys
import tempfile
import unittest
from unittest import TestCase
from unittest.mock import patch

import faiss
import numpy as np
from datasets import Dataset

from transformers import BartConfig, BartTokenizer, DPRConfig, DPRQuestionEncoderTokenizer, RagConfig
from transformers.file_utils import is_datasets_available, is_faiss_available, is_psutil_available, is_torch_available
from transformers.integrations import is_ray_available
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_ray


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # noqa: E402 # isort:skip

if is_torch_available():
    from distributed_pytorch_retriever import RagPyTorchDistributedRetriever  # noqa: E402 # isort:skip
else:
    _lowerCamelCase       =	None

if is_ray_available():
    import ray  # noqa: E402 # isort:skip
    from distributed_ray_retriever import RagRayDistributedRetriever, RayRetriever  # noqa: E402 # isort:skip
else:
    _lowerCamelCase       =	None
    _lowerCamelCase       =	None
    _lowerCamelCase       =	None




def 		lowerCAmelCase_	(  lowercase_   :							List[Any]		):

 '''simple docstring'''






 if not (is_datasets_available() and is_faiss_available() and is_psutil_available()):
  __SCREAMING_SNAKE_CASE :			str												=       unittest.skip('''test requires Datasets, Faiss, psutil'''		)(lowercase_		)
 return test_case






@require_distributed_retrieval
class 			snake_case		(   __UpperCAmelCase   ):

      def 						SCREAMING_SNAKE_CASE_			(			self   :List[str]						):
       __SCREAMING_SNAKE_CASE :			str												=       tempfile.mkdtemp()
       __SCREAMING_SNAKE_CASE :			List[Any]												=       8

       # DPR tok
       __SCREAMING_SNAKE_CASE :			Tuple												=       [
           '''[UNK]''',
           '''[CLS]''',
           '''[SEP]''',
           '''[PAD]''',
           '''[MASK]''',
           '''want''',
           '''##want''',
           '''##ed''',
           '''wa''',
           '''un''',
           '''runn''',
           '''##ing''',
           ''',''',
           '''low''',
           '''lowest''',
       ]
       __SCREAMING_SNAKE_CASE :			List[Any]												=       os.path.join(self.tmpdirname						,							'''dpr_tokenizer'''						)
       os.makedirs(_lowerCamelCase						,							exist_ok=_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			str												=       os.path.join(_lowerCamelCase						,							DPR_VOCAB_FILES_NAMES['''vocab_file''']						)
       with open(self.vocab_file						,							'''w'''						,							encoding='''utf-8'''						) as vocab_writer:
        vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]						)						)

       # BART tok
       __SCREAMING_SNAKE_CASE :			Tuple												=       [
           '''l''',
           '''o''',
           '''w''',
           '''e''',
           '''r''',
           '''s''',
           '''t''',
           '''i''',
           '''d''',
           '''n''',
           '''\u0120''',
           '''\u0120l''',
           '''\u0120n''',
           '''\u0120lo''',
           '''\u0120low''',
           '''er''',
           '''\u0120lowest''',
           '''\u0120newer''',
           '''\u0120wider''',
           '''<unk>''',
       ]
       __SCREAMING_SNAKE_CASE :			int												=       dict(zip(_lowerCamelCase						,							range(len(_lowerCamelCase						)						)						)						)
       __SCREAMING_SNAKE_CASE :			List[str]												=       ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       {'''unk_token''': '''<unk>'''}

       __SCREAMING_SNAKE_CASE :			int												=       os.path.join(self.tmpdirname						,							'''bart_tokenizer'''						)
       os.makedirs(_lowerCamelCase						,							exist_ok=_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			Any												=       os.path.join(_lowerCamelCase						,							BART_VOCAB_FILES_NAMES['''vocab_file''']						)
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       os.path.join(_lowerCamelCase						,							BART_VOCAB_FILES_NAMES['''merges_file''']						)
       with open(self.vocab_file						,							'''w'''						,							encoding='''utf-8'''						) as fp:
        fp.write(json.dumps(_lowerCamelCase						) + '''\n'''						)
       with open(self.merges_file						,							'''w'''						,							encoding='''utf-8'''						) as fp:
        fp.write('''\n'''.join(_lowerCamelCase						)						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Dict						):
       return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname						,							'''dpr_tokenizer'''						)						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						):
       return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname						,							'''bart_tokenizer'''						)						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :List[Any]						):
       shutil.rmtree(self.tmpdirname						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Optional[Any]						):
       __SCREAMING_SNAKE_CASE :			List[str]												=       Dataset.from_dict(
           {
               '''id''': ['''0''', '''1'''],
               '''text''': ['''foo''', '''bar'''],
               '''title''': ['''Foo''', '''Bar'''],
               '''embeddings''': [np.ones(self.retrieval_vector_size						), 2 * np.ones(self.retrieval_vector_size						)],
           }						)
       dataset.add_faiss_index('''embeddings'''						,							string_factory='''Flat'''						,							metric_type=faiss.METRIC_INNER_PRODUCT						)
       return dataset

      def 						SCREAMING_SNAKE_CASE_			(			self   :Any						,							_lowerCamelCase   :bool						,							_lowerCamelCase   :Union[str, Any]=1_2_3_4_5						):
       __SCREAMING_SNAKE_CASE :			Any												=       self.get_dummy_dataset()
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       RagConfig(
           retrieval_vector_size=self.retrieval_vector_size						,							question_encoder=DPRConfig().to_dict()						,							generator=BartConfig().to_dict()						,							)
       with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
        __SCREAMING_SNAKE_CASE :			Optional[int]												=       dataset
        __SCREAMING_SNAKE_CASE :			List[str]												=       RagPyTorchDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							)
        if init_retrieval:
         retriever.init_retrieval(_lowerCamelCase						)
       return retriever

      def 						SCREAMING_SNAKE_CASE_			(			self   :int						,							_lowerCamelCase   :bool						):
       # Have to run in local mode because sys.path modifications at top of
       # file are not propogated to remote workers.
       # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
       ray.init(local_mode=_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			List[str]												=       RagConfig(
           retrieval_vector_size=self.retrieval_vector_size						,							question_encoder=DPRConfig().to_dict()						,							generator=BartConfig().to_dict()						,							)
       __SCREAMING_SNAKE_CASE :			Any												=       ray.remote(_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			List[Any]												=       [remote_cls.remote() for _ in range(1						)]
       with patch('''transformers.models.rag.retrieval_rag.load_dataset'''						) as mock_load_dataset:
        __SCREAMING_SNAKE_CASE :			Tuple												=       self.get_dummy_dataset()
        __SCREAMING_SNAKE_CASE :			Optional[int]												=       RagRayDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							retrieval_workers=_lowerCamelCase						,							)
        if init_retrieval:
         retriever.init_retrieval()
       return retriever

      def 						SCREAMING_SNAKE_CASE_			(			self   :Union[str, Any]						,							_lowerCamelCase   :bool						,							_lowerCamelCase   :bool						,							_lowerCamelCase   :List[Any]=1_2_3_4_5						):
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       self.get_dummy_dataset()
       __SCREAMING_SNAKE_CASE :			Any												=       RagConfig(
           retrieval_vector_size=self.retrieval_vector_size						,							question_encoder=DPRConfig().to_dict()						,							generator=BartConfig().to_dict()						,							index_name='''custom'''						,							)
       if from_disk:
        __SCREAMING_SNAKE_CASE :			str												=       os.path.join(self.tmpdirname						,							'''dataset'''						)
        __SCREAMING_SNAKE_CASE :			str												=       os.path.join(self.tmpdirname						,							'''index.faiss'''						)
        dataset.get_index('''embeddings'''						).save(os.path.join(self.tmpdirname						,							'''index.faiss'''						)						)
        dataset.drop_index('''embeddings'''						)
        dataset.save_to_disk(os.path.join(self.tmpdirname						,							'''dataset'''						)						)
        del dataset
        __SCREAMING_SNAKE_CASE :			Optional[int]												=       RagPyTorchDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							)
       else:
        __SCREAMING_SNAKE_CASE :			Optional[Any]												=       RagPyTorchDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							index=CustomHFIndex(config.retrieval_vector_size						,							_lowerCamelCase						)						,							)
       if init_retrieval:
        retriever.init_retrieval(_lowerCamelCase						)
       return retriever

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						,							_lowerCamelCase   :bool						,							_lowerCamelCase   :bool						):
       # Have to run in local mode because sys.path modifications at top of
       # file are not propogated to remote workers.
       # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
       ray.init(local_mode=_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			str												=       self.get_dummy_dataset()
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       RagConfig(
           retrieval_vector_size=self.retrieval_vector_size						,							question_encoder=DPRConfig().to_dict()						,							generator=BartConfig().to_dict()						,							index_name='''custom'''						,							)
       __SCREAMING_SNAKE_CASE :			List[str]												=       ray.remote(_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       [remote_cls.remote() for _ in range(1						)]
       if from_disk:
        __SCREAMING_SNAKE_CASE :			List[Any]												=       os.path.join(self.tmpdirname						,							'''dataset'''						)
        __SCREAMING_SNAKE_CASE :			Any												=       os.path.join(self.tmpdirname						,							'''index.faiss'''						)
        dataset.get_index('''embeddings'''						).save(os.path.join(self.tmpdirname						,							'''index.faiss'''						)						)
        dataset.drop_index('''embeddings'''						)
        dataset.save_to_disk(os.path.join(self.tmpdirname						,							'''dataset'''						)						)
        del dataset
        __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       RagRayDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							retrieval_workers=_lowerCamelCase						,							index=CustomHFIndex.load_from_disk(
                vector_size=config.retrieval_vector_size						,							dataset_path=config.passages_path						,							index_path=config.index_path						,							)						,							)
       else:
        __SCREAMING_SNAKE_CASE :			int												=       RagRayDistributedRetriever(
            _lowerCamelCase						,							question_encoder_tokenizer=self.get_dpr_tokenizer()						,							generator_tokenizer=self.get_bart_tokenizer()						,							retrieval_workers=_lowerCamelCase						,							index=CustomHFIndex(config.retrieval_vector_size						,							_lowerCamelCase						)						,							)
       if init_retrieval:
        retriever.init_retrieval()
       return retriever

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						,							_lowerCamelCase   :RagRetriever						,							_lowerCamelCase   :np.array						,							_lowerCamelCase   :int						):
       __SCREAMING_SNAKE_CASE							,      __SCREAMING_SNAKE_CASE							,      __SCREAMING_SNAKE_CASE :			Optional[Any]												=       retriever.retrieve(_lowerCamelCase						,							n_docs=_lowerCamelCase						)
       self.assertEqual(retrieved_doc_embeds.shape						,							(2, n_docs, self.retrieval_vector_size)						)
       self.assertEqual(len(_lowerCamelCase						)						,							2						)
       self.assertEqual(sorted(doc_dicts[0]						)						,							['''embeddings''', '''id''', '''text''', '''title''']						)
       self.assertEqual(len(doc_dicts[0]['''id''']						)						,							_lowerCamelCase						)
       self.assertEqual(doc_dicts[0]['''id'''][0]						,							'''1'''						)  # max inner product is reached with second doc
       self.assertEqual(doc_dicts[1]['''id'''][0]						,							'''0'''						)  # max inner product is reached with first doc
       self.assertListEqual(doc_ids.tolist()						,							[[1], [0]]						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :int						):
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       1
       __SCREAMING_SNAKE_CASE :			Dict												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)

       self.distributed_retriever_check(
           self.get_dummy_pytorch_distributed_retriever(init_retrieval=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Dict						):
       __SCREAMING_SNAKE_CASE :			str												=       1
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)

       self.distributed_retriever_check(
           self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCamelCase						,							from_disk=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						,							)

      def 						SCREAMING_SNAKE_CASE_			(			self   :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       1
       __SCREAMING_SNAKE_CASE :			str												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)

       self.distributed_retriever_check(
           self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCamelCase						,							from_disk=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						,							)

      @require_ray
      def 						SCREAMING_SNAKE_CASE_			(			self   :Union[str, Any]						):
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       1
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)

       self.distributed_retriever_check(
           self.get_dummy_ray_distributed_retriever(init_retrieval=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						)
       ray.shutdown()

      @require_ray
      def 						SCREAMING_SNAKE_CASE_			(			self   :Optional[int]						):
       __SCREAMING_SNAKE_CASE :			str												=       1
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)
       with self.assertRaises(_lowerCamelCase						):
        self.distributed_retriever_check(
            self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCamelCase						,							from_disk=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						,							)
       ray.shutdown()



      @require_ray
      def 						SCREAMING_SNAKE_CASE_			(			self   :List[Any]						):
       __SCREAMING_SNAKE_CASE :			str												=       1
       __SCREAMING_SNAKE_CASE :			str												=       np.array(
           [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]						,							dtype=np.floataa						)

       self.distributed_retriever_check(
           self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCamelCase						,							from_disk=_lowerCamelCase						)						,							_lowerCamelCase						,							_lowerCamelCase						)
       ray.shutdown()








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


_lowerCamelCase       =	logging.get_logger(__name__)

_lowerCamelCase       =	{
    '''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 			snake_case		(   __UpperCAmelCase   ):
      lowerCamelCase__						= '''m2m_100'''
      lowerCamelCase__						= ['''past_key_values''']
      lowerCamelCase__						= {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}

      def __init__(			self   :int						,							_lowerCamelCase   :Union[str, Any]=1_2_8_1_1_2						,							_lowerCamelCase   :str=1_0_2_4						,							_lowerCamelCase   :Any=1_2						,							_lowerCamelCase   :Dict=4_0_9_6						,							_lowerCamelCase   :List[str]=1_6						,							_lowerCamelCase   :Union[str, Any]=1_2						,							_lowerCamelCase   :Any=4_0_9_6						,							_lowerCamelCase   :str=1_6						,							_lowerCamelCase   :Union[str, Any]=0.0_5						,							_lowerCamelCase   :Any=0.0_5						,							_lowerCamelCase   :int=True						,							_lowerCamelCase   :Dict=True						,							_lowerCamelCase   :List[str]="relu"						,							_lowerCamelCase   :List[Any]=1_0_2_4						,							_lowerCamelCase   :Dict=0.1						,							_lowerCamelCase   :List[Any]=0.1						,							_lowerCamelCase   :Any=0.0						,							_lowerCamelCase   :Tuple=0.0_2						,							_lowerCamelCase   :Dict=2						,							_lowerCamelCase   :List[str]=True						,							_lowerCamelCase   :Any=1						,							_lowerCamelCase   :Dict=0						,							_lowerCamelCase   :List[Any]=2						,							**_lowerCamelCase   :Optional[Any]						,							):
       __SCREAMING_SNAKE_CASE :			Any												=       vocab_size
       __SCREAMING_SNAKE_CASE :			Any												=       max_position_embeddings
       __SCREAMING_SNAKE_CASE :			int												=       d_model
       __SCREAMING_SNAKE_CASE :			List[Any]												=       encoder_ffn_dim
       __SCREAMING_SNAKE_CASE :			Dict												=       encoder_layers
       __SCREAMING_SNAKE_CASE :			int												=       encoder_attention_heads
       __SCREAMING_SNAKE_CASE :			Dict												=       decoder_ffn_dim
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       decoder_layers
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       decoder_attention_heads
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       dropout
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       attention_dropout
       __SCREAMING_SNAKE_CASE :			List[str]												=       activation_dropout
       __SCREAMING_SNAKE_CASE :			List[Any]												=       activation_function
       __SCREAMING_SNAKE_CASE :			Any												=       init_std
       __SCREAMING_SNAKE_CASE :			List[Any]												=       encoder_layerdrop
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       decoder_layerdrop
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       use_cache
       __SCREAMING_SNAKE_CASE :			List[str]												=       encoder_layers
       __SCREAMING_SNAKE_CASE :			str												=       scale_embedding  # scale factor will be sqrt(d_model) if True

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







class 			snake_case		(   __UpperCAmelCase   ):

      @property
      def 						SCREAMING_SNAKE_CASE_			(			self   :int						):
       __SCREAMING_SNAKE_CASE :			str												=       OrderedDict(
           [
               ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
               ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
           ]						)

       if self.use_past:
        __SCREAMING_SNAKE_CASE :			Dict												=       {0: '''batch'''}
        __SCREAMING_SNAKE_CASE :			Any												=       {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
       else:
        __SCREAMING_SNAKE_CASE :			int												=       {0: '''batch''', 1: '''decoder_sequence'''}
        __SCREAMING_SNAKE_CASE :			List[Any]												=       {0: '''batch''', 1: '''decoder_sequence'''}

       if self.use_past:
        self.fill_with_past_key_values_(_lowerCamelCase						,							direction='''inputs'''						)
       return common_inputs

      def 						SCREAMING_SNAKE_CASE_			(			self   :Tuple						,							_lowerCamelCase   :PreTrainedTokenizer						,							_lowerCamelCase   :int = -1						,							_lowerCamelCase   :int = -1						,							_lowerCamelCase   :bool = False						,							_lowerCamelCase   :Optional[TensorType] = None						,							):
       # Copied from OnnxConfig.generate_dummy_inputs
       # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       __SCREAMING_SNAKE_CASE :			List[Any]												=       compute_effective_axis_dimension(
           _lowerCamelCase						,							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
       __SCREAMING_SNAKE_CASE :			List[str]												=       tokenizer.num_special_tokens_to_add(_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			int												=       compute_effective_axis_dimension(
           _lowerCamelCase						,							fixed_dimension=OnnxConfig.default_fixed_sequence						,							num_token_to_add=_lowerCamelCase						)

       # Generate dummy inputs according to compute batch and sequence
       __SCREAMING_SNAKE_CASE :			int												=       [''' '''.join([tokenizer.unk_token]						) * seq_length] * batch_size
       __SCREAMING_SNAKE_CASE :			Union[str, Any]												=       dict(tokenizer(_lowerCamelCase						,							return_tensors=_lowerCamelCase						)						)
       return common_inputs

      def 						SCREAMING_SNAKE_CASE_			(			self   :str						,							_lowerCamelCase   :PreTrainedTokenizer						,							_lowerCamelCase   :int = -1						,							_lowerCamelCase   :int = -1						,							_lowerCamelCase   :bool = False						,							_lowerCamelCase   :Optional[TensorType] = None						,							):
       __SCREAMING_SNAKE_CASE :			Dict												=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           _lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						)

       # Generate decoder inputs
       __SCREAMING_SNAKE_CASE :			Dict												=       seq_length if not self.use_past else 1
       __SCREAMING_SNAKE_CASE :			Any												=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
           _lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						)
       __SCREAMING_SNAKE_CASE :			Optional[int]												=       {f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
       __SCREAMING_SNAKE_CASE :			Optional[Any]												=       dict(**_lowerCamelCase						,							**_lowerCamelCase						)

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

        __SCREAMING_SNAKE_CASE :			Any												=       torch.cat(
            [common_inputs['''decoder_attention_mask'''], torch.ones(_lowerCamelCase						,							_lowerCamelCase						)]						,							dim=1						)

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

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



      lowerCamelCase__						= _generate_dummy_inputs_for_default_and_seqaseq_lm

