

"""simple docstring"""

import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
			import jax.numpy as jnp







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						def __get__(self   ,		lowercase__   ,		lowercase__=None       ):
											# See docs.python.org/3/howto/descriptor.html#properties
											if obj is None:
																return self
											if self.fget is None:
																raise AttributeError("""unreadable attribute"""       )
											snake_case_					:		int 					=					"""__cached_""" + self.fget.__name__
											snake_case_					:		str 					=					getattr(lowercase__   ,		lowercase__   ,		lowercase__       )
											if cached is None:
																snake_case_					:		Any 					=					self.fget(lowercase__       )
																setattr(lowercase__   ,		lowercase__   ,		lowercase__       )
											return cached







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Dict			):



					"""simple docstring"""





					snake_case_					:		List[Any] 					=					val.lower()
					if val in {"y", "yes", "t", "true", "on", "1"}:
										return 1
					if val in {"n", "no", "f", "false", "off", "0"}:
										return 0
					raise ValueError(f'invalid truth value {val!r}'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[Any]			):



					"""simple docstring"""





					if is_torch_fx_proxy(SCREAMING_SNAKE_CASE__			):
										return True
					if is_torch_available():
										import torch

										if isinstance(SCREAMING_SNAKE_CASE__				,    torch.Tensor			):
															return True
					if is_tf_available():
										import tensorflow as tf

										if isinstance(SCREAMING_SNAKE_CASE__				,    tf.Tensor			):
															return True

					if is_flax_available():
										import jax.numpy as jnp
										from jax.core import Tracer

										if isinstance(SCREAMING_SNAKE_CASE__				,    (jnp.ndarray, Tracer)			):
															return True

					return isinstance(SCREAMING_SNAKE_CASE__				,    np.ndarray			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[Any]			):



					"""simple docstring"""





					return isinstance(SCREAMING_SNAKE_CASE__				,    np.ndarray			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Any			):



					"""simple docstring"""





					return _is_numpy(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[str]			):



					"""simple docstring"""





					import torch

					return isinstance(SCREAMING_SNAKE_CASE__				,    torch.Tensor			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[Any]			):



					"""simple docstring"""





					return False if not is_torch_available() else _is_torch(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[int]			):



					"""simple docstring"""





					import torch

					return isinstance(SCREAMING_SNAKE_CASE__				,    torch.device			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Union[str, Any]			):



					"""simple docstring"""





					return False if not is_torch_available() else _is_torch_device(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[Any]			):



					"""simple docstring"""





					import torch

					if isinstance(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			):
										if hasattr(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			):
															snake_case_					:		List[Any] 					=					getattr(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)
										else:
															return False
					return isinstance(SCREAMING_SNAKE_CASE__				,    torch.dtype			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  int			):



					"""simple docstring"""





					return False if not is_torch_available() else _is_torch_dtype(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Union[str, Any]			):



					"""simple docstring"""





					import tensorflow as tf

					return isinstance(SCREAMING_SNAKE_CASE__				,    tf.Tensor			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Any			):



					"""simple docstring"""





					return False if not is_tf_available() else _is_tensorflow(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  str			):



					"""simple docstring"""





					import tensorflow as tf

					# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
					if hasattr(SCREAMING_SNAKE_CASE__				,    """is_symbolic_tensor"""			):
										return tf.is_symbolic_tensor(SCREAMING_SNAKE_CASE__			)
					return type(SCREAMING_SNAKE_CASE__			) == tf.Tensor







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[Any]			):



					"""simple docstring"""





					return False if not is_tf_available() else _is_tf_symbolic_tensor(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  int			):



					"""simple docstring"""





					import jax.numpy as jnp  # noqa: F811

					return isinstance(SCREAMING_SNAKE_CASE__				,    jnp.ndarray			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Union[str, Any]			):



					"""simple docstring"""





					return False if not is_flax_available() else _is_jax(SCREAMING_SNAKE_CASE__			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Tuple			):



					"""simple docstring"""





					if isinstance(SCREAMING_SNAKE_CASE__				,    (dict, UserDict)			):
										return {k: to_py_obj(SCREAMING_SNAKE_CASE__			) for k, v in obj.items()}
					elif isinstance(SCREAMING_SNAKE_CASE__				,    (list, tuple)			):
										return [to_py_obj(SCREAMING_SNAKE_CASE__			) for o in obj]
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										return obj.numpy().tolist()
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return obj.detach().cpu().tolist()
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return np.asarray(SCREAMING_SNAKE_CASE__			).tolist()
					elif isinstance(SCREAMING_SNAKE_CASE__				,    (np.ndarray, np.number)			):  # tolist also works on 0d np arrays
										return obj.tolist()
					else:
										return obj







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Tuple			):



					"""simple docstring"""





					if isinstance(SCREAMING_SNAKE_CASE__				,    (dict, UserDict)			):
										return {k: to_numpy(SCREAMING_SNAKE_CASE__			) for k, v in obj.items()}
					elif isinstance(SCREAMING_SNAKE_CASE__				,    (list, tuple)			):
										return np.array(SCREAMING_SNAKE_CASE__			)
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										return obj.numpy()
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return obj.detach().cpu().numpy()
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return np.asarray(SCREAMING_SNAKE_CASE__			)
					else:
										return obj







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		str 					=					fields(self       )

											# Safety and consistency checks
											if not len(lowercase__       ):
																raise ValueError(f'{self.__class__.__name__} has no fields.'       )
											if not all(field.default is None for field in class_fields[1:]       ):
																raise ValueError(f'{self.__class__.__name__} should not have more than one required field.'       )

											snake_case_					:		Union[str, Any] 					=					getattr(self   ,		class_fields[0].name       )
											snake_case_					:		Any 					=					all(getattr(self   ,		field.name       ) is None for field in class_fields[1:]       )

											if other_fields_are_none and not is_tensor(lowercase__       ):
																if isinstance(lowercase__   ,		lowercase__       ):
																					snake_case_					:		Optional[Any] 					=					first_field.items()
																					snake_case_					:		int 					=					True
																else:
																					try:
																										snake_case_					:		Any 					=					iter(lowercase__       )
																										snake_case_					:		str 					=					True
																					except TypeError:
																										snake_case_					:		List[Any] 					=					False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
																if first_field_iterator:
																					for idx, element in enumerate(lowercase__       ):
																										if (
																										    not isinstance(lowercase__   ,		(list, tuple)       )
																										    or not len(lowercase__       ) == 2
																										    or not isinstance(element[0]   ,		lowercase__       )
																										):
																															if idx == 0:
																																				# If we do not have an iterator of key/values, set it as attribute
																																				snake_case_					:		Dict 					=					first_field
																															else:
																																				# If we have a mixed iterator, raise an error
																																				raise ValueError(
																																				    f'Cannot set key/value for {element}. It needs to be a tuple (key, value).'       )
																															break
																										setattr(self   ,		element[0]   ,		element[1]       )
																										if element[1] is not None:
																															snake_case_					:		Union[str, Any] 					=					element[1]
																elif first_field is not None:
																					snake_case_					:		Tuple 					=					first_field
											else:
																for field in class_fields:
																					snake_case_					:		Optional[int] 					=					getattr(self   ,		field.name       )
																					if v is not None:
																										snake_case_					:		Optional[int] 					=					v







						def __delitem__(self   ,		*lowercase__   ,		**lowercase__       ):
											raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'       )







						def 						__UpperCamelCase							(self   ,		*lowercase__   ,		**lowercase__       ):
											raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'       )







						def 						__UpperCamelCase							(self   ,		*lowercase__   ,		**lowercase__       ):
											raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.'       )







						def 						__UpperCamelCase							(self   ,		*lowercase__   ,		**lowercase__       ):
											raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.'       )







						def __getitem__(self   ,		lowercase__       ):
											if isinstance(lowercase__   ,		lowercase__       ):
																snake_case_					:		Union[str, Any] 					=					dict(self.items()       )
																return inner_dict[k]
											else:
																return self.to_tuple()[k]







						def __setattr__(self   ,		lowercase__   ,		lowercase__       ):
											if name in self.keys() and value is not None:
																# Don't call self.__setitem__ to avoid recursion errors
																super().__setitem__(lowercase__   ,		lowercase__       )
											super().__setattr__(lowercase__   ,		lowercase__       )







						def __setitem__(self   ,		lowercase__   ,		lowercase__       ):
											# Will raise a KeyException if needed
											super().__setitem__(lowercase__   ,		lowercase__       )
											# Don't call self.__setattr__ to avoid recursion errors
											super().__setattr__(lowercase__   ,		lowercase__       )







						def 						__UpperCamelCase							(self       ):
											return tuple(self[k] for k in self.keys()       )







class    __lowercase     (					_UpperCAmelCase					,    _UpperCAmelCase):







						"""simple docstring"""







						@classmethod
						def 						__UpperCamelCase							(cls   ,		lowercase__       ):
											raise ValueError(
											    f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()       )}'       )







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							str							       =		"""longest"""
						_A		:							Optional[Any]							       =		"""max_length"""
						_A		:							Optional[int]							       =		"""do_not_pad"""







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Any							       =		"""pt"""
						_A		:							Tuple							       =		"""tf"""
						_A		:							Any							       =		"""np"""
						_A		:							Dict							       =		"""jax"""







class    __lowercase     :







						"""simple docstring"""







						def __init__(self   ,		lowercase__       ):
											snake_case_					:		Any 					=					context_managers
											snake_case_					:		int 					=					ExitStack()







						def __enter__(self       ):
											for context_manager in self.context_managers:
																self.stack.enter_context(lowercase__       )







						def __exit__(self   ,		*lowercase__   ,		**lowercase__       ):
											self.stack.__exit__(*lowercase__   ,		**lowercase__       )







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Optional[Any]			):



					"""simple docstring"""





					snake_case_					:		Dict 					=					infer_framework(SCREAMING_SNAKE_CASE__			)
					if framework == "tf":
										snake_case_					:		Dict 					=					inspect.signature(model_class.call			)  # TensorFlow models
					elif framework == "pt":
										snake_case_					:		Union[str, Any] 					=					inspect.signature(model_class.forward			)  # PyTorch models
					else:
										snake_case_					:		List[str] 					=					inspect.signature(model_class.__call__			)  # Flax models

					for p in signature.parameters:
										if p == "return_loss" and signature.parameters[p].default is True:
															return True

					return False







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Union[str, Any]			):



					"""simple docstring"""





					snake_case_					:		Optional[int] 					=					model_class.__name__
					snake_case_					:		Tuple 					=					infer_framework(SCREAMING_SNAKE_CASE__			)
					if framework == "tf":
										snake_case_					:		int 					=					inspect.signature(model_class.call			)  # TensorFlow models
					elif framework == "pt":
										snake_case_					:		List[str] 					=					inspect.signature(model_class.forward			)  # PyTorch models
					else:
										snake_case_					:		List[Any] 					=					inspect.signature(model_class.__call__			)  # Flax models

					if "QuestionAnswering" in model_name:
										return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
					else:
										return [p for p in signature.parameters if "label" in p]







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  MutableMapping				,    SCREAMING_SNAKE_CASE__ :  str = ""				,    SCREAMING_SNAKE_CASE__ :  str = "."			):



					"""simple docstring"""





					def _flatten_dict(SCREAMING_SNAKE_CASE__ :  int				,    SCREAMING_SNAKE_CASE__ :  Optional[int]=""				,    SCREAMING_SNAKE_CASE__ :  List[Any]="."			):
										for k, v in d.items():
															snake_case_					:		Tuple 					=					str(SCREAMING_SNAKE_CASE__			) + delimiter + str(SCREAMING_SNAKE_CASE__			) if parent_key else k
															if v and isinstance(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			):
																				yield from flatten_dict(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    delimiter=SCREAMING_SNAKE_CASE__			).items()
															else:
																				yield key, v

					return dict(_flatten_dict(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)			)







@contextmanager
def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[Any]				,    SCREAMING_SNAKE_CASE__ :  bool = False			):



					"""simple docstring"""





					if use_temp_dir:
										with tempfile.TemporaryDirectory() as tmp_dir:
															yield tmp_dir
					else:
										yield working_dir







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[str]				,    SCREAMING_SNAKE_CASE__ :  Union[str, Any]=None			):



					"""simple docstring"""





					if is_numpy_array(SCREAMING_SNAKE_CASE__			):
										return np.transpose(SCREAMING_SNAKE_CASE__				,    axes=SCREAMING_SNAKE_CASE__			)
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return array.T if axes is None else array.permute(*SCREAMING_SNAKE_CASE__			)
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										import tensorflow as tf

										return tf.transpose(SCREAMING_SNAKE_CASE__				,    perm=SCREAMING_SNAKE_CASE__			)
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return jnp.transpose(SCREAMING_SNAKE_CASE__				,    axes=SCREAMING_SNAKE_CASE__			)
					else:
										raise ValueError(f'Type not supported for transpose: {type(SCREAMING_SNAKE_CASE__			)}.'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  int				,    SCREAMING_SNAKE_CASE__ :  Optional[Any]			):



					"""simple docstring"""





					if is_numpy_array(SCREAMING_SNAKE_CASE__			):
										return np.reshape(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return array.reshape(*SCREAMING_SNAKE_CASE__			)
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										import tensorflow as tf

										return tf.reshape(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return jnp.reshape(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)
					else:
										raise ValueError(f'Type not supported for reshape: {type(SCREAMING_SNAKE_CASE__			)}.'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Tuple				,    SCREAMING_SNAKE_CASE__ :  List[str]=None			):



					"""simple docstring"""





					if is_numpy_array(SCREAMING_SNAKE_CASE__			):
										return np.squeeze(SCREAMING_SNAKE_CASE__				,    axis=SCREAMING_SNAKE_CASE__			)
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return array.squeeze() if axis is None else array.squeeze(dim=SCREAMING_SNAKE_CASE__			)
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										import tensorflow as tf

										return tf.squeeze(SCREAMING_SNAKE_CASE__				,    axis=SCREAMING_SNAKE_CASE__			)
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return jnp.squeeze(SCREAMING_SNAKE_CASE__				,    axis=SCREAMING_SNAKE_CASE__			)
					else:
										raise ValueError(f'Type not supported for squeeze: {type(SCREAMING_SNAKE_CASE__			)}.'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[str]				,    SCREAMING_SNAKE_CASE__ :  Optional[int]			):



					"""simple docstring"""





					if is_numpy_array(SCREAMING_SNAKE_CASE__			):
										return np.expand_dims(SCREAMING_SNAKE_CASE__				,    SCREAMING_SNAKE_CASE__			)
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return array.unsqueeze(dim=SCREAMING_SNAKE_CASE__			)
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										import tensorflow as tf

										return tf.expand_dims(SCREAMING_SNAKE_CASE__				,    axis=SCREAMING_SNAKE_CASE__			)
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return jnp.expand_dims(SCREAMING_SNAKE_CASE__				,    axis=SCREAMING_SNAKE_CASE__			)
					else:
										raise ValueError(f'Type not supported for expand_dims: {type(SCREAMING_SNAKE_CASE__			)}.'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  List[str]			):



					"""simple docstring"""





					if is_numpy_array(SCREAMING_SNAKE_CASE__			):
										return np.size(SCREAMING_SNAKE_CASE__			)
					elif is_torch_tensor(SCREAMING_SNAKE_CASE__			):
										return array.numel()
					elif is_tf_tensor(SCREAMING_SNAKE_CASE__			):
										import tensorflow as tf

										return tf.size(SCREAMING_SNAKE_CASE__			)
					elif is_jax_tensor(SCREAMING_SNAKE_CASE__			):
										return array.size
					else:
										raise ValueError(f'Type not supported for expand_dims: {type(SCREAMING_SNAKE_CASE__			)}.'			)







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Union[str, Any]				,    SCREAMING_SNAKE_CASE__ :  List[str]			):



					"""simple docstring"""





					for key, value in auto_map.items():
										if isinstance(SCREAMING_SNAKE_CASE__				,    (tuple, list)			):
															snake_case_					:		Dict 					=					[f'{repo_id}--{v}' if (v is not None and """--""" not in v) else v for v in value]
										elif value is not None and "--" not in value:
															snake_case_					:		Union[str, Any] 					=					f'{repo_id}--{value}'

					return auto_map







def 							SCREAMING_SNAKE_CASE__      (		SCREAMING_SNAKE_CASE__ :  Tuple			):



					"""simple docstring"""





					for base_class in inspect.getmro(SCREAMING_SNAKE_CASE__			):
										snake_case_					:		Dict 					=					base_class.__module__
										snake_case_					:		int 					=					base_class.__name__
										if module.startswith("""tensorflow"""			) or module.startswith("""keras"""			) or name == "TFPreTrainedModel":
															return "tf"
										elif module.startswith("""torch"""			) or name == "PreTrainedModel":
															return "pt"
										elif module.startswith("""flax"""			) or module.startswith("""jax"""			) or name == "FlaxPreTrainedModel":
															return "flax"
					else:
										raise TypeError(f'Could not infer framework from class {model_class}.'			)









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




