






import copy

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


lowerCAmelCase_           = 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__ ):







		"""simple docstring"""



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


						'''simple docstring'''
						super().__init__(
						    bos_token_id=_SCREAMING_SNAKE_CASE						,pad_token_id=_SCREAMING_SNAKE_CASE						,eos_token_id=_SCREAMING_SNAKE_CASE						,decoder_start_token_id=_SCREAMING_SNAKE_CASE						,forced_eos_token_id=_SCREAMING_SNAKE_CASE						,is_encoder_decoder=_SCREAMING_SNAKE_CASE						,prefix=_SCREAMING_SNAKE_CASE						,vocab_size=_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE						,)
						assert (
						    "question_encoder" in kwargs and "generator" in kwargs
						), "Config has to be initialized with question_encoder and generator config"
						A	 =      kwargs.pop('question_encoder'		)
						A	 =      question_encoder_config.pop('model_type'		)
						A	 =      kwargs.pop('generator'		)
						A	 =      decoder_config.pop('model_type'		)

						from ..auto.configuration_auto import AutoConfig

						A	 =      AutoConfig.for_model(_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE		)
						A	 =      AutoConfig.for_model(_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE		)

						A	 =      reduce_loss
						A	 =      label_smoothing
						A	 =      exclude_bos_score
						A	 =      do_marginalize

						A	 =      title_sep
						A	 =      doc_sep
						A	 =      n_docs
						A	 =      max_combined_length

						A	 =      dataset
						A	 =      dataset_split
						A	 =      index_name

						A	 =      retrieval_vector_size
						A	 =      retrieval_batch_size
						A	 =      passages_path
						A	 =      index_path
						A	 =      use_dummy_dataset

						A	 =      output_retrieved

						A	 =      do_deduplication

						A	 =      use_cache

						if self.forced_eos_token_id is None:
										A	 =      getattr(self.generator						,'forced_eos_token_id'						,_SCREAMING_SNAKE_CASE		)
		@classmethod
		def       A(  cls		:       Dict						,_SCREAMING_SNAKE_CASE		:       PretrainedConfig						,_SCREAMING_SNAKE_CASE		:       PretrainedConfig						,**_SCREAMING_SNAKE_CASE		:       Union[str, Any]		)    ->   PretrainedConfig:


						'''simple docstring'''
						return cls(question_encoder=question_encoder_config.to_dict()						,generator=generator_config.to_dict()						,**_SCREAMING_SNAKE_CASE		)







		def       A(  self		:       Tuple		)    ->   Optional[int]:


						'''simple docstring'''
						A	 =      copy.deepcopy(self.__dict__		)
						A	 =      self.question_encoder.to_dict()
						A	 =      self.generator.to_dict()
						A	 =      self.__class__.model_type
						return output













import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class      UpperCamelCase (				snake_case__ ):







		"""simple docstring"""



		snake_case    =   ["image_processor", "tokenizer"]
		snake_case    =   "LayoutLMv2ImageProcessor"
		snake_case    =   ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")
		def __init__(  self		:       List[str]						,_SCREAMING_SNAKE_CASE		:       List[str]=None						,_SCREAMING_SNAKE_CASE		:       Optional[int]=None						,**_SCREAMING_SNAKE_CASE		:       Tuple		)    ->   List[str]:


						'''simple docstring'''
						if "feature_extractor" in kwargs:
										warnings.warn(
										    'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
										    ' instead.'						,_SCREAMING_SNAKE_CASE						,)
										A	 =      kwargs.pop('feature_extractor'		)

						A	 =      image_processor if image_processor is not None else feature_extractor
						if image_processor is None:
										raise ValueError('You need to specify an `image_processor`.'		)
						if tokenizer is None:
										raise ValueError('You need to specify a `tokenizer`.'		)

						super().__init__(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		)
		def __call__(  self		:       Union[str, Any]						,_SCREAMING_SNAKE_CASE		:       Optional[int]						,_SCREAMING_SNAKE_CASE		:       Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None						,_SCREAMING_SNAKE_CASE		:       Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None						,_SCREAMING_SNAKE_CASE		:       Union[List[List[int]], List[List[List[int]]]] = None						,_SCREAMING_SNAKE_CASE		:       Optional[Union[List[int], List[List[int]]]] = None						,_SCREAMING_SNAKE_CASE		:       bool = True						,_SCREAMING_SNAKE_CASE		:       Union[bool, str, PaddingStrategy] = False						,_SCREAMING_SNAKE_CASE		:       Union[bool, str, TruncationStrategy] = None						,_SCREAMING_SNAKE_CASE		:       Optional[int] = None						,_SCREAMING_SNAKE_CASE		:       int = 0						,_SCREAMING_SNAKE_CASE		:       Optional[int] = None						,_SCREAMING_SNAKE_CASE		:       Optional[bool] = None						,_SCREAMING_SNAKE_CASE		:       Optional[bool] = None						,_SCREAMING_SNAKE_CASE		:       bool = False						,_SCREAMING_SNAKE_CASE		:       bool = False						,_SCREAMING_SNAKE_CASE		:       bool = False						,_SCREAMING_SNAKE_CASE		:       bool = False						,_SCREAMING_SNAKE_CASE		:       bool = True						,_SCREAMING_SNAKE_CASE		:       Optional[Union[str, TensorType]] = None						,**_SCREAMING_SNAKE_CASE		:       Tuple						,)    ->   BatchEncoding:


						'''simple docstring'''
						# verify input
						if self.image_processor.apply_ocr and (boxes is not None):
										raise ValueError(
										    'You cannot provide bounding boxes '
										    'if you initialized the image processor with apply_ocr set to True.'		)

						if self.image_processor.apply_ocr and (word_labels is not None):
										raise ValueError(
										    'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'		)

						if return_overflowing_tokens is True and return_offsets_mapping is False:
										raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.'		)

						# first, apply the image processor
						A	 =      self.image_processor(images=_SCREAMING_SNAKE_CASE						,return_tensors=_SCREAMING_SNAKE_CASE		)

						# second, apply the tokenizer
						if text is not None and self.image_processor.apply_ocr and text_pair is None:
										if isinstance(_SCREAMING_SNAKE_CASE						,_SCREAMING_SNAKE_CASE		):
														A	 =      [text]  # add batch dimension (as the image processor always adds a batch dimension)
										A	 =      features['words']

						A	 =      self.tokenizer(
						    text=text if text is not None else features['words']						,text_pair=text_pair if text_pair is not None else None						,boxes=boxes if boxes is not None else features['boxes']						,word_labels=_SCREAMING_SNAKE_CASE						,add_special_tokens=_SCREAMING_SNAKE_CASE						,padding=_SCREAMING_SNAKE_CASE						,truncation=_SCREAMING_SNAKE_CASE						,max_length=_SCREAMING_SNAKE_CASE						,stride=_SCREAMING_SNAKE_CASE						,pad_to_multiple_of=_SCREAMING_SNAKE_CASE						,return_token_type_ids=_SCREAMING_SNAKE_CASE						,return_attention_mask=_SCREAMING_SNAKE_CASE						,return_overflowing_tokens=_SCREAMING_SNAKE_CASE						,return_special_tokens_mask=_SCREAMING_SNAKE_CASE						,return_offsets_mapping=_SCREAMING_SNAKE_CASE						,return_length=_SCREAMING_SNAKE_CASE						,verbose=_SCREAMING_SNAKE_CASE						,return_tensors=_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE						,)

						# add pixel values
						A	 =      features.pop('pixel_values'		)
						if return_overflowing_tokens is True:
										A	 =      self.get_overflowing_images(_SCREAMING_SNAKE_CASE						,encoded_inputs['overflow_to_sample_mapping']		)
						A	 =      images

						return encoded_inputs
		def       A(  self		:       Dict						,_SCREAMING_SNAKE_CASE		:       Optional[Any]						,_SCREAMING_SNAKE_CASE		:       Optional[Any]		)    ->   Dict:


						'''simple docstring'''
						# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
						A	 =      []
						for sample_idx in overflow_to_sample_mapping:
										images_with_overflow.append(images[sample_idx]		)

						if len(_SCREAMING_SNAKE_CASE		) != len(_SCREAMING_SNAKE_CASE		):
										raise ValueError(
										    'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
										    f' {len(_SCREAMING_SNAKE_CASE		)} and {len(_SCREAMING_SNAKE_CASE		)}'		)

						return images_with_overflow
		def       A(  self		:       List[str]						,*_SCREAMING_SNAKE_CASE		:       str						,**_SCREAMING_SNAKE_CASE		:       Union[str, Any]		)    ->   Tuple:


						'''simple docstring'''
						return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE		)
		def       A(  self		:       Dict						,*_SCREAMING_SNAKE_CASE		:       Tuple						,**_SCREAMING_SNAKE_CASE		:       int		)    ->   int:


						'''simple docstring'''
						return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE						,**_SCREAMING_SNAKE_CASE		)
		@property
		def       A(  self		:       Any		)    ->   Union[str, Any]:


						'''simple docstring'''
						return ["input_ids", "bbox", "attention_mask", "image"]
		@property
		def       A(  self		:       Dict		)    ->   int:


						'''simple docstring'''
						warnings.warn(
						    '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'						,_SCREAMING_SNAKE_CASE						,)
						return self.image_processor_class







		@property
		def       A(  self		:       Optional[int]		)    ->   Union[str, Any]:


						'''simple docstring'''
						warnings.warn(
						    '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'						,_SCREAMING_SNAKE_CASE						,)
						return self.image_processor





