

"""simple docstring"""

import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow


if is_tf_available():
			import tensorflow as tf

if is_keras_nlp_available():
			from transformers.models.gpta import TFGPTaTokenizer


a_			   =					['''gpt2''']
a_			   =					'''gpt2'''

if is_tf_available():







			class    __lowercase     (					tf.Module):







									"""simple docstring"""







									def __init__(self   ,		lowercase__       ):
														super().__init__()
														snake_case_					:		Any 					=					tokenizer
														snake_case_					:		Union[str, Any] 					=					AutoConfig.from_pretrained(lowercase__       )
														snake_case_					:		Union[str, Any] 					=					TFGPTaLMHeadModel.from_config(lowercase__       )







									@tf.function(input_signature=(tf.TensorSpec((None,)   ,		tf.string   ,		name="""text"""       ),)       )
									def 						__UpperCamelCase							(self   ,		lowercase__       ):
														snake_case_					:		str 					=					self.tokenizer(lowercase__       )
														snake_case_					:		str 					=					tokenized["""input_ids"""].to_tensor()

														snake_case_					:		Optional[int] 					=					tf.cast(input_ids_dense > 0   ,		tf.intaa       )
														# input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])

														snake_case_					:		str 					=					self.model(input_ids=lowercase__   ,		attention_mask=lowercase__       )["""logits"""]

														return outputs







@require_tf
@require_keras_nlp
class    __lowercase     (					unittest.TestCase):







						"""simple docstring"""







						def 						__UpperCamelCase							(self       ):
											super().setUp()

											snake_case_					:		List[Any] 					=					[GPTaTokenizer.from_pretrained(lowercase__       ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
											snake_case_					:		Optional[Any] 					=					[TFGPTaTokenizer.from_pretrained(lowercase__       ) for checkpoint in TOKENIZER_CHECKPOINTS]
											assert len(self.tokenizers       ) == len(self.tf_tokenizers       )

											snake_case_					:		Any 					=					[
											    """This is a straightforward English test sentence.""",
											    """This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.""",
											    """Now we're going to add some Chinese: 一 二 三 一二三""",
											    """And some much more rare Chinese: 齉 堃 齉堃""",
											    """Je vais aussi écrire en français pour tester les accents""",
											    """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""",
											]
											snake_case_					:		Union[str, Any] 					=					list(zip(self.test_sentences   ,		self.test_sentences[::-1]       )       )







						def 						__UpperCamelCase							(self       ):
											for tokenizer, tf_tokenizer in zip(self.tokenizers   ,		self.tf_tokenizers       ):
																for test_inputs in self.test_sentences:
																					snake_case_					:		List[str] 					=					tokenizer([test_inputs]   ,		return_tensors="""tf"""       )
																					snake_case_					:		Tuple 					=					tf_tokenizer([test_inputs]       )

																					for key in python_outputs.keys():
																										# convert them to numpy to avoid messing with ragged tensors
																										snake_case_					:		Dict 					=					python_outputs[key].numpy()
																										snake_case_					:		Dict 					=					tf_outputs[key].numpy()

																										self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape       )       )
																										self.assertTrue(tf.reduce_all(tf.cast(lowercase__   ,		tf.intaa       ) == tf_outputs_values       )       )







						@slow
						def 						__UpperCamelCase							(self       ):
											for tf_tokenizer in self.tf_tokenizers:
																snake_case_					:		int 					=					tf.function(lowercase__       )
																for test_inputs in self.test_sentences:
																					snake_case_					:		int 					=					tf.constant(lowercase__       )
																					snake_case_					:		str 					=					compiled_tokenizer(lowercase__       )
																					snake_case_					:		Dict 					=					tf_tokenizer(lowercase__       )

																					for key in eager_outputs.keys():
																										self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]       )       )







						@slow
						def 						__UpperCamelCase							(self       ):
											for tf_tokenizer in self.tf_tokenizers:
																snake_case_					:		Optional[int] 					=					ModelToSave(tokenizer=lowercase__       )
																snake_case_					:		Optional[Any] 					=					tf.convert_to_tensor([self.test_sentences[0]]       )
																snake_case_					:		Tuple 					=					model.serving(lowercase__       )  # Build model with some sample inputs
																with TemporaryDirectory() as tempdir:
																					snake_case_					:		int 					=					Path(lowercase__       ) / """saved.model"""
																					tf.saved_model.save(lowercase__   ,		lowercase__   ,		signatures={"""serving_default""": model.serving}       )
																					snake_case_					:		Tuple 					=					tf.saved_model.load(lowercase__       )
																snake_case_					:		List[Any] 					=					loaded_model.signatures["""serving_default"""](lowercase__       )["""output_0"""]
																# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
																self.assertTrue(tf.reduce_all(out == loaded_output       )       )







						@slow
						def 						__UpperCamelCase							(self       ):
											for tf_tokenizer in self.tf_tokenizers:
																snake_case_					:		List[str] 					=					tf.convert_to_tensor([self.test_sentences[0]]       )
																snake_case_					:		List[Any] 					=					tf_tokenizer(lowercase__       )  # Build model with some sample inputs

																snake_case_					:		Any 					=					tf_tokenizer.get_config()
																snake_case_					:		List[Any] 					=					TFGPTaTokenizer.from_config(lowercase__       )
																snake_case_					:		List[str] 					=					model_from_config(lowercase__       )

																for key in from_config_output.keys():
																					self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]       )       )







						@slow
						def 						__UpperCamelCase							(self       ):
											for tf_tokenizer in self.tf_tokenizers:
																# for the test to run
																snake_case_					:		Tuple 					=					12_31_23

																for max_length in [3, 5, 10_24]:
																					snake_case_					:		Tuple 					=					tf.convert_to_tensor([self.test_sentences[0]]       )
																					snake_case_					:		List[Any] 					=					tf_tokenizer(lowercase__   ,		max_length=lowercase__       )

																					snake_case_					:		Union[str, Any] 					=					out["""input_ids"""].numpy().shape[1]

																					assert out_length == max_length









"""simple docstring"""

import copy

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


a_			   =					r'''
    [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
    can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.

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







@add_start_docstrings(_UpperCAmelCase)
class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Optional[int]							       =		"""rag"""
						_A		:							Optional[Any]							       =		True







						def __init__(self   ,		lowercase__=None   ,		lowercase__=True   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=" / "   ,		lowercase__=" // "   ,		lowercase__=5   ,		lowercase__=3_00   ,		lowercase__=7_68   ,		lowercase__=8   ,		lowercase__="wiki_dpr"   ,		lowercase__="train"   ,		lowercase__="compressed"   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=0.0   ,		lowercase__=True   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=False   ,		lowercase__=True   ,		lowercase__=None   ,		**lowercase__   ,		):
											super().__init__(
											    bos_token_id=lowercase__   ,		pad_token_id=lowercase__   ,		eos_token_id=lowercase__   ,		decoder_start_token_id=lowercase__   ,		forced_eos_token_id=lowercase__   ,		is_encoder_decoder=lowercase__   ,		prefix=lowercase__   ,		vocab_size=lowercase__   ,		**lowercase__   ,		)
											assert (
											    "question_encoder" in kwargs and "generator" in kwargs
											), "Config has to be initialized with question_encoder and generator config"
											snake_case_					:		List[Any] 					=					kwargs.pop("""question_encoder"""       )
											snake_case_					:		Tuple 					=					question_encoder_config.pop("""model_type"""       )
											snake_case_					:		List[str] 					=					kwargs.pop("""generator"""       )
											snake_case_					:		List[str] 					=					decoder_config.pop("""model_type"""       )

											from ..auto.configuration_auto import AutoConfig

											snake_case_					:		List[str] 					=					AutoConfig.for_model(lowercase__   ,		**lowercase__       )
											snake_case_					:		Tuple 					=					AutoConfig.for_model(lowercase__   ,		**lowercase__       )

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

											snake_case_					:		Union[str, Any] 					=					title_sep
											snake_case_					:		int 					=					doc_sep
											snake_case_					:		int 					=					n_docs
											snake_case_					:		List[str] 					=					max_combined_length

											snake_case_					:		Tuple 					=					dataset
											snake_case_					:		int 					=					dataset_split
											snake_case_					:		str 					=					index_name

											snake_case_					:		List[str] 					=					retrieval_vector_size
											snake_case_					:		Dict 					=					retrieval_batch_size
											snake_case_					:		str 					=					passages_path
											snake_case_					:		Union[str, Any] 					=					index_path
											snake_case_					:		Tuple 					=					use_dummy_dataset

											snake_case_					:		Dict 					=					output_retrieved

											snake_case_					:		str 					=					do_deduplication

											snake_case_					:		Any 					=					use_cache

											if self.forced_eos_token_id is None:
																snake_case_					:		Any 					=					getattr(self.generator   ,		"""forced_eos_token_id"""   ,		lowercase__       )







						@classmethod
						def 						__UpperCamelCase							(cls   ,		lowercase__   ,		lowercase__   ,		**lowercase__       ):
											return cls(question_encoder=question_encoder_config.to_dict()   ,		generator=generator_config.to_dict()   ,		**lowercase__       )







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Optional[Any] 					=					copy.deepcopy(self.__dict__       )
											snake_case_					:		Any 					=					self.question_encoder.to_dict()
											snake_case_					:		Dict 					=					self.generator.to_dict()
											snake_case_					:		Union[str, Any] 					=					self.__class__.model_type
											return output




