





'''simple docstring'''






import copy

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings


__UpperCamelCase					    =	R"\n    [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n    can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n    Args:\n        title_sep (`str`, *optional*, defaults to  `\" / \"`):\n            Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n        doc_sep (`str`, *optional*, defaults to  `\" // \"`):\n            Separator inserted between the text of the retrieved document and the original input when calling\n            [`RagRetriever`].\n        n_docs (`int`, *optional*, defaults to 5):\n            Number of documents to retrieve.\n        max_combined_length (`int`, *optional*, defaults to 300):\n            Max length of contextualized input returned by [`~RagRetriever.__call__`].\n        retrieval_vector_size (`int`, *optional*, defaults to 768):\n            Dimensionality of the document embeddings indexed by [`RagRetriever`].\n        retrieval_batch_size (`int`, *optional*, defaults to 8):\n            Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n            [`RagRetriever`].\n        dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):\n            A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n            using `datasets.list_datasets()`).\n        dataset_split (`str`, *optional*, defaults to `\"train\"`)\n            Which split of the `dataset` to load.\n        index_name (`str`, *optional*, defaults to `\"compressed\"`)\n            The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and\n            `\"compressed\"`.\n        index_path (`str`, *optional*)\n            The path to the serialized faiss index on disk.\n        passages_path (`str`, *optional*):\n            A path to text passages compatible with the faiss index. Required if using\n            [`~models.rag.retrieval_rag.LegacyIndex`]\n        use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n            Whether to load a \"dummy\" variant of the dataset specified by `dataset`.\n        label_smoothing (`float`, *optional*, defaults to 0.0):\n            Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n            in the loss calculation. If set to 0, no label smoothing is performed.\n        do_marginalize (`bool`, *optional*, defaults to `False`):\n            If `True`, the logits are marginalized over all documents by making use of\n            `torch.nn.functional.log_softmax`.\n        reduce_loss (`bool`, *optional*, defaults to `False`):\n            Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n        do_deduplication (`bool`, *optional*, defaults to `True`):\n            Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n            set to `False` if used while training with distributed backend.\n        exclude_bos_score (`bool`, *optional*, defaults to `False`):\n            Whether or not to disregard the BOS token when computing the loss.\n        output_retrieved(`bool`, *optional*, defaults to `False`):\n            If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n            `context_attention_mask` are returned. See returned tensors for more detail.\n        use_cache (`bool`, *optional*, defaults to `True`):\n            Whether or not the model should return the last key/values attentions (not used by all models).\n        forced_eos_token_id (`int`, *optional*):\n            The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n            `eos_token_id`.\n"




@add_start_docstrings(__lowercase		)
class  _A (					__lowercase		):
		lowercase__:   Optional[int]				     =   '''rag'''
		lowercase__:   str				     =   True

		def __init__(   self					:   Tuple  ,      __magic_name__					:   List[str]=None  ,      __magic_name__					:   List[Any]=True  ,      __magic_name__					:   int=None  ,      __magic_name__					:   Optional[int]=None  ,      __magic_name__					:   Any=None  ,      __magic_name__					:   List[Any]=None  ,      __magic_name__					:   str=None  ,      __magic_name__					:   Optional[int]=" / "  ,      __magic_name__					:   Dict=" // "  ,      __magic_name__					:   List[str]=5  ,      __magic_name__					:   Tuple=3_00  ,      __magic_name__					:   Optional[int]=7_68  ,      __magic_name__					:   Tuple=8  ,      __magic_name__					:   Tuple="wiki_dpr"  ,      __magic_name__					:   Tuple="train"  ,      __magic_name__					:   Tuple="compressed"  ,      __magic_name__					:   Optional[Any]=None  ,      __magic_name__					:   Optional[Any]=None  ,      __magic_name__					:   Any=False  ,      __magic_name__					:   Union[str, Any]=False  ,      __magic_name__					:   Tuple=0.0  ,      __magic_name__					:   Any=True  ,      __magic_name__					:   Tuple=False  ,      __magic_name__					:   Tuple=False  ,      __magic_name__					:   Optional[Any]=False  ,      __magic_name__					:   Optional[int]=True  ,      __magic_name__					:   Dict=None  ,      **__magic_name__					:   List[str]  ,      )					->    Optional[int]:


					"""simple docstring"""

					super().__init__(
					    bos_token_id=__UpperCamelCase  ,      pad_token_id=__UpperCamelCase  ,      eos_token_id=__UpperCamelCase  ,      decoder_start_token_id=__UpperCamelCase  ,      forced_eos_token_id=__UpperCamelCase  ,      is_encoder_decoder=__UpperCamelCase  ,      prefix=__UpperCamelCase  ,      vocab_size=__UpperCamelCase  ,      **__UpperCamelCase  ,      )
					assert (
					    "question_encoder" in kwargs and "generator" in kwargs
					), "Config has to be initialized with question_encoder and generator config"
					__snake_case					:      str							      =     kwargs.pop("""question_encoder"""			)
					__snake_case					:      Any							      =     question_encoder_config.pop("""model_type"""			)
					__snake_case					:      Tuple							      =     kwargs.pop("""generator"""			)
					__snake_case					:      Union[str, Any]							      =     decoder_config.pop("""model_type"""			)

					from ..auto.configuration_auto import AutoConfig

					__snake_case					:      Union[str, Any]							      =     AutoConfig.for_model(__UpperCamelCase  ,      **__UpperCamelCase			)
					__snake_case					:      Dict							      =     AutoConfig.for_model(__UpperCamelCase  ,      **__UpperCamelCase			)

					__snake_case					:      Optional[int]							      =     reduce_loss
					__snake_case					:      str							      =     label_smoothing
					__snake_case					:      Union[str, Any]							      =     exclude_bos_score
					__snake_case					:      int							      =     do_marginalize

					__snake_case					:      Any							      =     title_sep
					__snake_case					:      Any							      =     doc_sep
					__snake_case					:      Any							      =     n_docs
					__snake_case					:      Optional[int]							      =     max_combined_length

					__snake_case					:      int							      =     dataset
					__snake_case					:      Dict							      =     dataset_split
					__snake_case					:      int							      =     index_name

					__snake_case					:      Any							      =     retrieval_vector_size
					__snake_case					:      List[Any]							      =     retrieval_batch_size
					__snake_case					:      List[str]							      =     passages_path
					__snake_case					:      List[Any]							      =     index_path
					__snake_case					:      Union[str, Any]							      =     use_dummy_dataset

					__snake_case					:      str							      =     output_retrieved

					__snake_case					:      int							      =     do_deduplication

					__snake_case					:      int							      =     use_cache

					if self.forced_eos_token_id is None:
								__snake_case					:      List[Any]							      =     getattr(self.generator  ,      """forced_eos_token_id"""  ,      __UpperCamelCase			)

		@classmethod
		def 	lowercase__     (   cls					:   Tuple  ,      __magic_name__					:   PretrainedConfig  ,      __magic_name__					:   PretrainedConfig  ,      **__magic_name__					:   List[str]			)					->    int:


					"""simple docstring"""

					return cls(question_encoder=question_encoder_config.to_dict()  ,      generator=generator_config.to_dict()  ,      **__UpperCamelCase			)

		def 	lowercase__     (   self					:   int			)					->    Tuple:


					"""simple docstring"""

					__snake_case					:      int							      =     copy.deepcopy(self.__dict__			)
					__snake_case					:      Tuple							      =     self.question_encoder.to_dict()
					__snake_case					:      List[str]							      =     self.generator.to_dict()
					__snake_case					:      Dict							      =     self.__class__.model_type
					return output




import os
import unittest

from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow

from ...test_tokenization_common import TokenizerTesterMixin





class    __A(					UpperCAmelCase  ,		unittest.TestCase							):
					SCREAMING_SNAKE_CASE           =     ProphetNetTokenizer
					SCREAMING_SNAKE_CASE           =     False

					def  lowercase__   (						self       :  Optional[Any] ):
												super().setUp()

												lowerCamelCase_					=       [
												    """[UNK]""",
												    """[CLS]""",
												    """[SEP]""",
												    """[PAD]""",
												    """[MASK]""",
												    """want""",
												    """##want""",
												    """##ed""",
												    """wa""",
												    """un""",
												    """runn""",
												    """##ing""",
												    """,""",
												    """low""",
												    """lowest""",
												]
												lowerCamelCase_					=       os.path.join(self.tmpdirname ,       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] ) )

					def  lowercase__   (						self       :  int ,       __UpperCamelCase       :  int ):
												lowerCamelCase_					=       """UNwant\u00E9d,running"""
												lowerCamelCase_					=       """unwanted, running"""
												return input_text, output_text

					def  lowercase__   (						self       :  Optional[int] ):
												lowerCamelCase_					=       self.tokenizer_class(self.vocab_file )

												lowerCamelCase_					=       tokenizer.tokenize("""UNwant\u00E9d,running""" )
												self.assertListEqual(__UpperCamelCase ,       ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
												self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCamelCase ) ,       [9, 6, 7, 1_2, 1_0, 1_1] )

					def  lowercase__   (						self       :  Tuple ):
												lowerCamelCase_					=       BasicTokenizer()

												self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) ,       ["""ah""", """\u535A""", """\u63A8""", """zz"""] )

					def  lowercase__   (						self       :  Union[str, Any] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHeLLo!how  \n Are yoU?  """ ) ,       ["""hello""", """!""", """how""", """are""", """you""", """?"""] )
												self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,       ["""hello"""] )

					def  lowercase__   (						self       :  Optional[Any] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase ,       strip_accents=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHäLLo!how  \n Are yoU?  """ ) ,       ["""hällo""", """!""", """how""", """are""", """you""", """?"""] )
												self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,       ["""h\u00E9llo"""] )

					def  lowercase__   (						self       :  Optional[int] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase ,       strip_accents=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHäLLo!how  \n Are yoU?  """ ) ,       ["""hallo""", """!""", """how""", """are""", """you""", """?"""] )
												self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,       ["""hello"""] )

					def  lowercase__   (						self       :  List[Any] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHäLLo!how  \n Are yoU?  """ ) ,       ["""hallo""", """!""", """how""", """are""", """you""", """?"""] )
												self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) ,       ["""hello"""] )

					def  lowercase__   (						self       :  List[str] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHeLLo!how  \n Are yoU?  """ ) ,       ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )

					def  lowercase__   (						self       :  int ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase ,       strip_accents=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHäLLo!how  \n Are yoU?  """ ) ,       ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )

					def  lowercase__   (						self       :  Optional[Any] ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase ,       strip_accents=__UpperCamelCase )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHäLLo!how  \n Are yoU?  """ ) ,       ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )

					def  lowercase__   (						self       :  Dict ):
												lowerCamelCase_					=       BasicTokenizer(do_lower_case=__UpperCamelCase ,       never_split=["""[UNK]"""] )

												self.assertListEqual(
												    tokenizer.tokenize(""" \tHeLLo!how  \n Are yoU? [UNK]""" ) ,       ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] )

					def  lowercase__   (						self       :  List[str] ):
												lowerCamelCase_					=       ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""]

												lowerCamelCase_					=       {}
												for i, token in enumerate(__UpperCamelCase ):
																			lowerCamelCase_					=       i
												lowerCamelCase_					=       WordpieceTokenizer(vocab=__UpperCamelCase ,       unk_token="""[UNK]""" )

												self.assertListEqual(tokenizer.tokenize("""""" ) ,       [] )

												self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) ,       ["""un""", """##want""", """##ed""", """runn""", """##ing"""] )

												self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) ,       ["""[UNK]""", """runn""", """##ing"""] )

					@require_torch
					def  lowercase__   (						self       :  int ):
												lowerCamelCase_					=       self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" )

												lowerCamelCase_					=       ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
												lowerCamelCase_					=       [1_0_3_7, 2_1_4_6, 2_0_4_2_3, 2_0_0_5, 7_6_8_0, 7_8_4_9, 3_9_8_9, 1_0_1_2, 1_0_2]
												lowerCamelCase_					=       tokenizer(__UpperCamelCase ,       padding=__UpperCamelCase ,       return_tensors="""pt""" )
												self.assertIsInstance(__UpperCamelCase ,       __UpperCamelCase )
												lowerCamelCase_					=       list(batch.input_ids.numpy()[0] )
												self.assertListEqual(__UpperCamelCase ,       __UpperCamelCase )

												self.assertEqual((2, 9) ,       batch.input_ids.shape )
												self.assertEqual((2, 9) ,       batch.attention_mask.shape )

					def  lowercase__   (						self       :  List[str] ):
												self.assertTrue(_is_whitespace(""" """ ) )
												self.assertTrue(_is_whitespace("""\t""" ) )
												self.assertTrue(_is_whitespace("""\r""" ) )
												self.assertTrue(_is_whitespace("""\n""" ) )
												self.assertTrue(_is_whitespace("""\u00A0""" ) )

												self.assertFalse(_is_whitespace("""A""" ) )
												self.assertFalse(_is_whitespace("""-""" ) )

					def  lowercase__   (						self       :  Union[str, Any] ):
												self.assertTrue(_is_control("""\u0005""" ) )

												self.assertFalse(_is_control("""A""" ) )
												self.assertFalse(_is_control(""" """ ) )
												self.assertFalse(_is_control("""\t""" ) )
												self.assertFalse(_is_control("""\r""" ) )

					def  lowercase__   (						self       :  Tuple ):
												self.assertTrue(_is_punctuation("""-""" ) )
												self.assertTrue(_is_punctuation("""$""" ) )
												self.assertTrue(_is_punctuation("""`""" ) )
												self.assertTrue(_is_punctuation(""".""" ) )

												self.assertFalse(_is_punctuation("""A""" ) )
												self.assertFalse(_is_punctuation(""" """ ) )



					@slow
					def  lowercase__   (						self       :  str ):
												lowerCamelCase_					=       self.tokenizer_class.from_pretrained("""microsoft/prophetnet-large-uncased""" )

												lowerCamelCase_					=       tokenizer.encode("""sequence builders""" ,       add_special_tokens=__UpperCamelCase )
												lowerCamelCase_					=       tokenizer.encode("""multi-sequence build""" ,       add_special_tokens=__UpperCamelCase )

												lowerCamelCase_					=       tokenizer.build_inputs_with_special_tokens(__UpperCamelCase )
												lowerCamelCase_					=       tokenizer.build_inputs_with_special_tokens(__UpperCamelCase ,       __UpperCamelCase )

												assert encoded_sentence == text + [1_0_2]
												assert encoded_pair == text + [1_0_2] + text_a + [1_0_2]





