






import copy

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


_UpperCamelCase			:	Any								=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(__snake_case							)
class 						UpperCAmelCase__ (							__snake_case							):
		__snake_case      :       Optional[Any]     =   "rag"
		__snake_case      :       Optional[int]     =   True







		def __init__(					self       ,A__=None       ,A__=True       ,A__=None       ,A__=None       ,A__=None       ,A__=None       ,A__=None       ,A__=" / "       ,A__=" // "       ,A__=5       ,A__=300       ,A__=768       ,A__=8       ,A__="wiki_dpr"       ,A__="train"       ,A__="compressed"       ,A__=None       ,A__=None       ,A__=False       ,A__=False       ,A__=0.0       ,A__=True       ,A__=False       ,A__=False       ,A__=False       ,A__=True       ,A__=None       ,**A__       ,):
						super().__init__(
						    bos_token_id=A__       ,pad_token_id=A__       ,eos_token_id=A__       ,decoder_start_token_id=A__       ,forced_eos_token_id=A__       ,is_encoder_decoder=A__       ,prefix=A__       ,vocab_size=A__       ,**A__       ,)
						assert (
						    "question_encoder" in kwargs and "generator" in kwargs
						), "Config has to be initialized with question_encoder and generator config"
						_A	:				Tuple   =      kwargs.pop('''question_encoder'''		)
						_A	:				Optional[int]   =      question_encoder_config.pop('''model_type'''		)
						_A	:				int   =      kwargs.pop('''generator'''		)
						_A	:				List[Any]   =      decoder_config.pop('''model_type'''		)

						from ..auto.configuration_auto import AutoConfig

						_A	:				Optional[int]   =      AutoConfig.for_model(A__       ,**A__		)
						_A	:				Dict   =      AutoConfig.for_model(A__       ,**A__		)

						_A	:				Dict   =      reduce_loss
						_A	:				Union[str, Any]   =      label_smoothing
						_A	:				List[Any]   =      exclude_bos_score
						_A	:				Union[str, Any]   =      do_marginalize

						_A	:				Any   =      title_sep
						_A	:				Optional[Any]   =      doc_sep
						_A	:				Dict   =      n_docs
						_A	:				Dict   =      max_combined_length

						_A	:				Tuple   =      dataset
						_A	:				Optional[Any]   =      dataset_split
						_A	:				Optional[int]   =      index_name

						_A	:				Optional[Any]   =      retrieval_vector_size
						_A	:				Optional[int]   =      retrieval_batch_size
						_A	:				str   =      passages_path
						_A	:				Union[str, Any]   =      index_path
						_A	:				str   =      use_dummy_dataset

						_A	:				Union[str, Any]   =      output_retrieved

						_A	:				Dict   =      do_deduplication

						_A	:				Union[str, Any]   =      use_cache

						if self.forced_eos_token_id is None:
										_A	:				List[Any]   =      getattr(self.generator       ,'''forced_eos_token_id'''       ,A__		)







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







		def  A__      (					self		):
						_A	:				str   =      copy.deepcopy(self.__dict__		)
						_A	:				Tuple   =      self.question_encoder.to_dict()
						_A	:				Dict   =      self.generator.to_dict()
						_A	:				Tuple   =      self.__class__.model_type
						return output











import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pytest

from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex

from .utils import require_elasticsearch, require_faiss


_UpperCamelCase			:	Optional[Any]								=pytest.mark.integration






@require_faiss
class 						UpperCAmelCase__ (							__snake_case							):







		def  A__      (					self		):
						_A	:				Any   =      Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(A__		) for x in np.arange(30		).tolist()]}		)
						return dset







		def  A__      (					self		):
						import faiss

						_A	:				Dataset   =      self._create_dummy_dataset()
						_A	:				List[str]   =      dset.map(
						    lambda A__       ,A__		: {"vecs": i * np.ones(5       ,dtype=np.floataa		)}       ,with_indices=A__       ,keep_in_memory=A__		)
						_A	:				Tuple   =      dset.add_faiss_index('''vecs'''       ,batch_size=100       ,metric_type=faiss.METRIC_INNER_PRODUCT		)
						_A  ,				_A	:				List[Any]   =      dset.get_nearest_examples('''vecs'''       ,np.ones(5       ,dtype=np.floataa		)		)
						self.assertEqual(examples['''filename'''][0]       ,'''my_name-train_29'''		)
						dset.drop_index('''vecs'''		)







		def  A__      (					self		):
						import faiss

						_A	:				Dataset   =      self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)		) * np.arange(30		).reshape(-1       ,1		)       ,index_name='''vecs'''       ,batch_size=100       ,metric_type=faiss.METRIC_INNER_PRODUCT       ,)
						_A  ,				_A	:				Tuple   =      dset.get_nearest_examples('''vecs'''       ,np.ones(5       ,dtype=np.floataa		)		)
						self.assertEqual(examples['''filename'''][0]       ,'''my_name-train_29'''		)







		def  A__      (					self		):
						import faiss

						_A	:				Dataset   =      self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)		) * np.arange(30		).reshape(-1       ,1		)       ,index_name='''vecs'''       ,metric_type=faiss.METRIC_INNER_PRODUCT       ,)

						# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
						# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
						# see https://bugs.python.org/issue14243 and
						# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
						with tempfile.NamedTemporaryFile(delete=A__		) as tmp_file:
										dset.save_faiss_index('''vecs'''       ,tmp_file.name		)
										dset.load_faiss_index('''vecs2'''       ,tmp_file.name		)
						os.unlink(tmp_file.name		)

						_A  ,				_A	:				Optional[int]   =      dset.get_nearest_examples('''vecs2'''       ,np.ones(5       ,dtype=np.floataa		)		)
						self.assertEqual(examples['''filename'''][0]       ,'''my_name-train_29'''		)







		def  A__      (					self		):
						_A	:				Dataset   =      self._create_dummy_dataset()
						dset.add_faiss_index_from_external_arrays(
						    external_arrays=np.ones((30, 5)		) * np.arange(30		).reshape(-1       ,1		)       ,index_name='''vecs'''		)
						dset.drop_index('''vecs'''		)
						self.assertRaises(A__       ,partial(dset.get_nearest_examples       ,'''vecs2'''       ,np.ones(5       ,dtype=np.floataa		)		)		)







		def  A__      (					self		):
						from elasticsearch import Elasticsearch

						_A	:				Dataset   =      self._create_dummy_dataset()
						with patch('''elasticsearch.Elasticsearch.search'''		) as mocked_search, patch(
						    '''elasticsearch.client.IndicesClient.create'''		) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk'''		) as mocked_bulk:
										_A	:				str   =      {'''acknowledged''': True}
										mocked_bulk.return_value([(True, None)] * 30		)
										_A	:				Optional[Any]   =      {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}}
										_A	:				Optional[Any]   =      Elasticsearch()

										dset.add_elasticsearch_index('''filename'''       ,es_client=A__		)
										_A  ,				_A	:				Tuple   =      dset.get_nearest_examples('''filename'''       ,'''my_name-train_29'''		)
										self.assertEqual(examples['''filename'''][0]       ,'''my_name-train_29'''		)






@require_faiss
class 						UpperCAmelCase__ (							__snake_case							):







		def  A__      (					self		):
						import faiss

						_A	:				Union[str, Any]   =      FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT		)

						# add vectors
						index.add_vectors(np.eye(5       ,dtype=np.floataa		)		)
						self.assertIsNotNone(index.faiss_index		)
						self.assertEqual(index.faiss_index.ntotal       ,5		)
						index.add_vectors(np.zeros((5, 5)       ,dtype=np.floataa		)		)
						self.assertEqual(index.faiss_index.ntotal       ,10		)

						# single query
						_A	:				str   =      np.zeros(5       ,dtype=np.floataa		)
						_A	:				Dict   =      1
						_A  ,				_A	:				Optional[int]   =      index.search(A__		)
						self.assertRaises(A__       ,index.search       ,query.reshape(-1       ,1		)		)
						self.assertGreater(scores[0]       ,0		)
						self.assertEqual(indices[0]       ,1		)

						# batched queries
						_A	:				Optional[Any]   =      np.eye(5       ,dtype=np.floataa		)[::-1]
						_A  ,				_A	:				Dict   =      index.search_batch(A__		)
						self.assertRaises(A__       ,index.search_batch       ,queries[0]		)
						_A	:				Tuple   =      [scores[0] for scores in total_scores]
						_A	:				List[str]   =      [indices[0] for indices in total_indices]
						self.assertGreater(np.min(A__		)       ,0		)
						self.assertListEqual([4, 3, 2, 1, 0]       ,A__		)







		def  A__      (					self		):
						import faiss

						_A	:				List[Any]   =      FaissIndex(string_factory='''Flat'''		)
						index.add_vectors(np.eye(5       ,dtype=np.floataa		)		)
						self.assertIsInstance(index.faiss_index       ,faiss.IndexFlat		)
						_A	:				str   =      FaissIndex(string_factory='''LSH'''		)
						index.add_vectors(np.eye(5       ,dtype=np.floataa		)		)
						self.assertIsInstance(index.faiss_index       ,faiss.IndexLSH		)
						with self.assertRaises(A__		):
										_A	:				List[str]   =      FaissIndex(string_factory='''Flat'''       ,custom_index=faiss.IndexFlat(5		)		)







		def  A__      (					self		):
						import faiss

						_A	:				Any   =      faiss.IndexFlat(5		)
						_A	:				Any   =      FaissIndex(custom_index=A__		)
						index.add_vectors(np.eye(5       ,dtype=np.floataa		)		)
						self.assertIsInstance(index.faiss_index       ,faiss.IndexFlat		)







		def  A__      (					self		):
						import faiss

						_A	:				Optional[int]   =      FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT		)
						index.add_vectors(np.eye(5       ,dtype=np.floataa		)		)

						# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
						# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
						# see https://bugs.python.org/issue14243 and
						# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
						with tempfile.NamedTemporaryFile(delete=A__		) as tmp_file:
										index.save(tmp_file.name		)
										_A	:				str   =      FaissIndex.load(tmp_file.name		)
						os.unlink(tmp_file.name		)

						_A	:				Tuple   =      np.zeros(5       ,dtype=np.floataa		)
						_A	:				Tuple   =      1
						_A  ,				_A	:				Union[str, Any]   =      index.search(A__		)
						self.assertGreater(scores[0]       ,0		)
						self.assertEqual(indices[0]       ,1		)



@require_faiss
def  a__ (__lowercase							:List[Any]   )		-> int:
				import faiss

				_A	:				Any   =      FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT   )
				index.add_vectors(np.eye(5					,  dtype=np.floataa   )   )

				_A	:				List[Any]   =      '''index.faiss'''
				_A	:				Any   =      f"""mock://{index_name}"""
				index.save(__lowercase					,  storage_options=mockfs.storage_options   )
				_A	:				Dict   =      FaissIndex.load(__lowercase					,  storage_options=mockfs.storage_options   )

				_A	:				Tuple   =      np.zeros(5					,  dtype=np.floataa   )
				_A	:				Union[str, Any]   =      1
				_A  ,				_A	:				Optional[int]   =      index.search(__lowercase   )
				assert scores[0] > 0
				assert indices[0] == 1






@require_elasticsearch
class 						UpperCAmelCase__ (							__snake_case							):







		def  A__      (					self		):
						from elasticsearch import Elasticsearch

						with patch('''elasticsearch.Elasticsearch.search'''		) as mocked_search, patch(
						    '''elasticsearch.client.IndicesClient.create'''		) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk'''		) as mocked_bulk:
										_A	:				Tuple   =      Elasticsearch()
										_A	:				Tuple   =      {'''acknowledged''': True}
										_A	:				int   =      ElasticSearchIndex(es_client=A__		)
										mocked_bulk.return_value([(True, None)] * 3		)
										index.add_documents(['''foo''', '''bar''', '''foobar''']		)

										# single query
										_A	:				Dict   =      '''foo'''
										_A	:				Optional[Any]   =      {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}}
										_A  ,				_A	:				Optional[Any]   =      index.search(A__		)
										self.assertEqual(scores[0]       ,1		)
										self.assertEqual(indices[0]       ,0		)

										# single query with timeout
										_A	:				Union[str, Any]   =      '''foo'''
										_A	:				Optional[int]   =      {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}}
										_A  ,				_A	:				Optional[int]   =      index.search(A__       ,request_timeout=30		)
										self.assertEqual(scores[0]       ,1		)
										self.assertEqual(indices[0]       ,0		)

										# batched queries
										_A	:				Dict   =      ['''foo''', '''bar''', '''foobar''']
										_A	:				Dict   =      {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}}
										_A  ,				_A	:				Dict   =      index.search_batch(A__		)
										_A	:				Union[str, Any]   =      [scores[0] for scores in total_scores]
										_A	:				Tuple   =      [indices[0] for indices in total_indices]
										self.assertGreater(np.min(A__		)       ,0		)
										self.assertListEqual([1, 1, 1]       ,A__		)

										# batched queries with timeout
										_A	:				Union[str, Any]   =      ['''foo''', '''bar''', '''foobar''']
										_A	:				int   =      {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}}
										_A  ,				_A	:				str   =      index.search_batch(A__       ,request_timeout=30		)
										_A	:				Dict   =      [scores[0] for scores in total_scores]
										_A	:				List[str]   =      [indices[0] for indices in total_indices]
										self.assertGreater(np.min(A__		)       ,0		)
										self.assertListEqual([1, 1, 1]       ,A__		)



