




'''simple docstring'''

import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
							import bitsandbytes as bnb
							import torch
							import torch.nn as nn

							from ..pytorch_utils import ConvaD

if is_accelerate_available():
							from accelerate import init_empty_weights
							from accelerate.utils import find_tied_parameters

a  :				Optional[Any]									=  logging.get_logger(__name__)


def 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None	)		->					Dict:

					'''simple docstring'''

					if "." in tensor_name:
										snake_case_									=				tensor_name.split('''.'''	)
										for split in splits[:-1]:
															snake_case_									=				getattr(__UpperCAmelCase,      __UpperCAmelCase	)
															if new_module is None:
																				raise ValueError(F"{module} has no attribute {split}."	)
															snake_case_									=				new_module
										snake_case_									=				splits[-1]

					if tensor_name not in module._parameters and tensor_name not in module._buffers:
										raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}."	)
					snake_case_									=				tensor_name in module._buffers
					snake_case_									=				getattr(__UpperCAmelCase,      __UpperCAmelCase	)

					if old_value.device == torch.device('''meta'''	) and device not in ["meta", torch.device('''meta'''	)] and value is None:
										raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}."	)

					snake_case_									=				False
					snake_case_									=				False
					if is_buffer or not is_bitsandbytes_available():
										snake_case_									=				False
										snake_case_									=				False
					else:
										snake_case_									=				hasattr(bnb.nn,      '''Params4bit'''	) and isinstance(module._parameters[tensor_name],      bnb.nn.Paramsabit	)
										snake_case_									=				isinstance(module._parameters[tensor_name],      bnb.nn.IntaParams	)

					if is_abit or is_abit:
										snake_case_									=				module._parameters[tensor_name]
										if param.device.type != "cuda":
															if value is None:
																				snake_case_									=				old_value.to(__UpperCAmelCase	)
															elif isinstance(__UpperCAmelCase,      torch.Tensor	):
																				snake_case_									=				value.to('''cpu'''	)
																				if value.dtype == torch.inta:
																									snake_case_									=				version.parse(importlib.metadata.version('''bitsandbytes'''	)	) > version.parse(
																									    '''0.37.2'''	)
																									if not is_abit_serializable:
																														raise ValueError(
																														    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
																														    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''	)
															else:
																				snake_case_									=				torch.tensor(__UpperCAmelCase,      device='''cpu'''	)

															# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
															# Since weights are saved in the correct "orientation", we skip transposing when loading.
															if issubclass(module.source_cls,      __UpperCAmelCase	) and fpaa_statistics is None:
																				snake_case_									=				new_value.T

															snake_case_									=				old_value.__dict__
															if is_abit:
																				snake_case_									=				bnb.nn.IntaParams(__UpperCAmelCase,      requires_grad=__UpperCAmelCase,      **__UpperCAmelCase	).to(__UpperCAmelCase	)
															elif is_abit:
																				snake_case_									=				bnb.nn.Paramsabit(__UpperCAmelCase,      requires_grad=__UpperCAmelCase,      **__UpperCAmelCase	).to(__UpperCAmelCase	)

															snake_case_									=				new_value
															if fpaa_statistics is not None:
																				setattr(module.weight,      '''SCB''',      fpaa_statistics.to(__UpperCAmelCase	)	)

					else:
										if value is None:
															snake_case_									=				old_value.to(__UpperCAmelCase	)
										elif isinstance(__UpperCAmelCase,      torch.Tensor	):
															snake_case_									=				value.to(__UpperCAmelCase	)
										else:
															snake_case_									=				torch.tensor(__UpperCAmelCase,      device=__UpperCAmelCase	)

										if is_buffer:
															snake_case_									=				new_value
										else:
															snake_case_									=				nn.Parameter(__UpperCAmelCase,      requires_grad=old_value.requires_grad	)
															snake_case_									=				new_value


def 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=False	)		->					List[str]:

					'''simple docstring'''

					for name, module in model.named_children():
										if current_key_name is None:
															snake_case_									=				[]
										current_key_name.append(__UpperCAmelCase	)

										if (isinstance(__UpperCAmelCase,      nn.Linear	) or isinstance(__UpperCAmelCase,      __UpperCAmelCase	)) and name not in modules_to_not_convert:
															# Check if the current key is not in the `modules_to_not_convert`
															if not any(key in '''.'''.join(__UpperCAmelCase	) for key in modules_to_not_convert	):
																				with init_empty_weights():
																									if isinstance(__UpperCAmelCase,      __UpperCAmelCase	):
																														snake_case_			,snake_case_									=				module.weight.shape
																									else:
																														snake_case_									=				module.in_features
																														snake_case_									=				module.out_features

																									if quantization_config.quantization_method() == "llm_int8":
																														snake_case_									=				bnb.nn.LinearabitLt(
																														    __UpperCAmelCase,      __UpperCAmelCase,      module.bias is not None,      has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight,      threshold=quantization_config.llm_inta_threshold,      )
																														snake_case_									=				True
																									else:
																														if (
																														    quantization_config.llm_inta_skip_modules is not None
																														    and name in quantization_config.llm_inta_skip_modules
																														):
																																			pass
																														else:
																																			snake_case_									=				bnb.nn.Linearabit(
																																			    __UpperCAmelCase,      __UpperCAmelCase,      module.bias is not None,      quantization_config.bnb_abit_compute_dtype,      compress_statistics=quantization_config.bnb_abit_use_double_quant,      quant_type=quantization_config.bnb_abit_quant_type,      )
																																			snake_case_									=				True
                    # Store the module class in case we need to transpose the weight later
																									snake_case_									=				type(__UpperCAmelCase	)
																									# Force requires grad to False to avoid unexpected errors
																									model._modules[name].requires_grad_(__UpperCAmelCase	)
										if len(list(module.children()	)	) > 0:
															snake_case_			,snake_case_									=				_replace_with_bnb_linear(
															    __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      has_been_replaced=__UpperCAmelCase,      )
										# Remove the last key for recursion
										current_key_name.pop(-1	)
					return model, has_been_replaced


def 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=None	)		->					str:

					'''simple docstring'''

					snake_case_									=				['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
					snake_case_			,snake_case_									=				_replace_with_bnb_linear(
					    __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase	)

					if not has_been_replaced:
										logger.warning(
										    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
										    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
										    ''' a bug.'''	)

					return model


def 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Optional[Any]:

					'''simple docstring'''

					warnings.warn(
					    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''',      __UpperCAmelCase,      )
					return replace_with_bnb_linear(*__UpperCAmelCase,      **__UpperCAmelCase	)


def 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Dict:

					'''simple docstring'''

					warnings.warn(
					    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''',      __UpperCAmelCase,      )
					return set_module_quantized_tensor_to_device(*__UpperCAmelCase,      **__UpperCAmelCase	)


def 		__magic_name__    (	__UpperCAmelCase	)		->					str:

					'''simple docstring'''

					snake_case_									=				deepcopy(__UpperCAmelCase	)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
					tied_model.tie_weights()

					snake_case_									=				find_tied_parameters(__UpperCAmelCase	)
					# For compatibility with Accelerate < 0.18
					if isinstance(__UpperCAmelCase,      __UpperCAmelCase	):
										snake_case_									=				sum(list(tied_params.values()	),      []	) + list(tied_params.keys()	)
					else:
										snake_case_									=				sum(__UpperCAmelCase,      []	)
					snake_case_									=				len(__UpperCAmelCase	) > 0

					# Check if it is a base model
					snake_case_									=				not hasattr(__UpperCAmelCase,      model.base_model_prefix	)

					# Ignore this for base models (BertModel, GPT2Model, etc.)
					if (not has_tied_params) and is_base_model:
										return []

					# otherwise they have an attached head
					snake_case_									=				list(model.named_children()	)
					snake_case_									=				[list_modules[-1][0]]

					# add last module together with tied weights
					snake_case_									=				set(__UpperCAmelCase	) - set(__UpperCAmelCase	)
					snake_case_									=				list(set(__UpperCAmelCase	)	) + list(__UpperCAmelCase	)

					# remove ".weight" from the keys
					snake_case_									=				['''.weight''', '''.bias''']
					snake_case_									=				[]
					for name in list_untouched:
										for name_to_remove in names_to_remove:
															if name_to_remove in name:
																				snake_case_									=				name.replace(__UpperCAmelCase,      ''''''	)
										filtered_module_names.append(__UpperCAmelCase	)

					return filtered_module_names







'''simple docstring'''

import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
							import faiss






@require_faiss
class 						a				(   _lowerCamelCase     ):


				def   A_ (		self    :					str					):
									snake_case_									=				tempfile.mkdtemp()
									snake_case_									=				8

									# DPR tok
									snake_case_									=				[
									    '''[UNK]''',
									    '''[CLS]''',
									    '''[SEP]''',
									    '''[PAD]''',
									    '''[MASK]''',
									    '''want''',
									    '''##want''',
									    '''##ed''',
									    '''wa''',
									    '''un''',
									    '''runn''',
									    '''##ing''',
									    ''',''',
									    '''low''',
									    '''lowest''',
									]
									snake_case_									=				os.path.join(self.tmpdirname       ,				'''dpr_tokenizer'''					)
									os.makedirs(lowercase_       ,				exist_ok=lowercase_					)
									snake_case_									=				os.path.join(lowercase_       ,				DPR_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]					)					)

									# BART tok
									snake_case_									=				[
									    '''l''',
									    '''o''',
									    '''w''',
									    '''e''',
									    '''r''',
									    '''s''',
									    '''t''',
									    '''i''',
									    '''d''',
									    '''n''',
									    '''\u0120''',
									    '''\u0120l''',
									    '''\u0120n''',
									    '''\u0120lo''',
									    '''\u0120low''',
									    '''er''',
									    '''\u0120lowest''',
									    '''\u0120newer''',
									    '''\u0120wider''',
									    '''<unk>''',
									]
									snake_case_									=				dict(zip(lowercase_       ,				range(len(lowercase_					)					)					)					)
									snake_case_									=				['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
									snake_case_									=				{'''unk_token''': '''<unk>'''}

									snake_case_									=				os.path.join(self.tmpdirname       ,				'''bart_tokenizer'''					)
									os.makedirs(lowercase_       ,				exist_ok=lowercase_					)
									snake_case_									=				os.path.join(lowercase_       ,				BART_VOCAB_FILES_NAMES['''vocab_file''']					)
									snake_case_									=				os.path.join(lowercase_       ,				BART_VOCAB_FILES_NAMES['''merges_file''']					)
									with open(self.vocab_file       ,				'''w'''       ,				encoding='''utf-8'''					) as fp:
														fp.write(json.dumps(lowercase_					) + '''\n'''					)
									with open(self.merges_file       ,				'''w'''       ,				encoding='''utf-8'''					) as fp:
														fp.write('''\n'''.join(lowercase_					)					)


				def   A_ (		self    :					Union[str, Any]					):
									return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname       ,				'''dpr_tokenizer'''					)					)


				def   A_ (		self    :					Union[str, Any]					):
									return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname       ,				'''dpr_tokenizer'''					)					)


				def   A_ (		self    :					int					):
									return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname       ,				'''bart_tokenizer'''					)					)


				def   A_ (		self    :					str					):
									shutil.rmtree(self.tmpdirname					)


				def   A_ (		self    :					str					):
									snake_case_									=				Dataset.from_dict(
									    {
									        '''id''': ['''0''', '''1'''],
									        '''text''': ['''foo''', '''bar'''],
									        '''title''': ['''Foo''', '''Bar'''],
									        '''embeddings''': [np.ones(self.retrieval_vector_size					), 2 * np.ones(self.retrieval_vector_size					)],
									    }					)
									dataset.add_faiss_index('''embeddings'''       ,				string_factory='''Flat'''       ,				metric_type=faiss.METRIC_INNER_PRODUCT					)
									return dataset


				def   A_ (		self    :					str					):
									snake_case_									=				self.get_dummy_dataset()
									snake_case_									=				RagConfig(
									    retrieval_vector_size=self.retrieval_vector_size       ,				question_encoder=DPRConfig().to_dict()       ,				generator=BartConfig().to_dict()       ,				)
									with patch('''transformers.models.rag.retrieval_rag.load_dataset'''					) as mock_load_dataset:
														snake_case_									=				dataset
														snake_case_									=				RagRetriever(
														    lowercase_       ,				question_encoder_tokenizer=self.get_dpr_tokenizer()       ,				generator_tokenizer=self.get_bart_tokenizer()       ,				)
									return retriever


				def   A_ (		self    :					str       ,				lowercase_    :					bool					):
									snake_case_									=				self.get_dummy_dataset()
									snake_case_									=				RagConfig(
									    retrieval_vector_size=self.retrieval_vector_size       ,				question_encoder=DPRConfig().to_dict()       ,				generator=BartConfig().to_dict()       ,				index_name='''custom'''       ,				)
									if from_disk:
														snake_case_									=				os.path.join(self.tmpdirname       ,				'''dataset'''					)
														snake_case_									=				os.path.join(self.tmpdirname       ,				'''index.faiss'''					)
														dataset.get_index('''embeddings'''					).save(os.path.join(self.tmpdirname       ,				'''index.faiss'''					)					)
														dataset.drop_index('''embeddings'''					)
														dataset.save_to_disk(os.path.join(self.tmpdirname       ,				'''dataset'''					)					)
														del dataset
														snake_case_									=				RagRetriever(
														    lowercase_       ,				question_encoder_tokenizer=self.get_dpr_tokenizer()       ,				generator_tokenizer=self.get_bart_tokenizer()       ,				)
									else:
														snake_case_									=				RagRetriever(
														    lowercase_       ,				question_encoder_tokenizer=self.get_dpr_tokenizer()       ,				generator_tokenizer=self.get_bart_tokenizer()       ,				index=CustomHFIndex(config.retrieval_vector_size       ,				lowercase_					)       ,				)
									return retriever


				def   A_ (		self    :					Tuple					):
									snake_case_									=				Dataset.from_dict(
									    {
									        '''id''': ['''0''', '''1'''],
									        '''text''': ['''foo''', '''bar'''],
									        '''title''': ['''Foo''', '''Bar'''],
									        '''embeddings''': [np.ones(self.retrieval_vector_size + 1					), 2 * np.ones(self.retrieval_vector_size + 1					)],
									    }					)
									dataset.add_faiss_index('''embeddings'''       ,				string_factory='''Flat'''       ,				metric_type=faiss.METRIC_INNER_PRODUCT					)

									snake_case_									=				os.path.join(self.tmpdirname       ,				'''hf_bert_base.hnswSQ8_correct_phi_128.c_index'''					)
									dataset.save_faiss_index('''embeddings'''       ,				index_file_name + '''.index.dpr'''					)
									pickle.dump(dataset['''id''']       ,				open(index_file_name + '''.index_meta.dpr'''       ,				'''wb'''					)					)

									snake_case_									=				os.path.join(self.tmpdirname       ,				'''psgs_w100.tsv.pkl'''					)
									snake_case_									=				{sample['''id''']: [sample['''text'''], sample['''title''']] for sample in dataset}
									pickle.dump(lowercase_       ,				open(lowercase_       ,				'''wb'''					)					)

									snake_case_									=				RagConfig(
									    retrieval_vector_size=self.retrieval_vector_size       ,				question_encoder=DPRConfig().to_dict()       ,				generator=BartConfig().to_dict()       ,				index_name='''legacy'''       ,				index_path=self.tmpdirname       ,				)
									snake_case_									=				RagRetriever(
									    lowercase_       ,				question_encoder_tokenizer=self.get_dpr_tokenizer()       ,				generator_tokenizer=self.get_bart_tokenizer()					)
									return retriever


				def   A_ (		self    :					Optional[Any]					):
									snake_case_									=				1
									snake_case_									=				self.get_dummy_canonical_hf_index_retriever()
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_			,snake_case_			,snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=lowercase_					)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertEqual(len(lowercase_					)       ,				2					)
									self.assertEqual(sorted(doc_dicts[0]					)       ,				['''embeddings''', '''id''', '''text''', '''title''']					)
									self.assertEqual(len(doc_dicts[0]['''id''']					)       ,				lowercase_					)
									self.assertEqual(doc_dicts[0]['''id'''][0]       ,				'''1'''					)  # max inner product is reached with second doc
									self.assertEqual(doc_dicts[1]['''id'''][0]       ,				'''0'''					)  # max inner product is reached with first doc
									self.assertListEqual(doc_ids.tolist()       ,				[[1], [0]]					)


				def   A_ (		self    :					str					):
									snake_case_									=				self.get_dummy_canonical_hf_index_retriever()
									with tempfile.TemporaryDirectory() as tmp_dirname:
														with patch('''transformers.models.rag.retrieval_rag.load_dataset'''					) as mock_load_dataset:
																			snake_case_									=				self.get_dummy_dataset()
																			retriever.save_pretrained(lowercase_					)
																			snake_case_									=				RagRetriever.from_pretrained(lowercase_					)
																			self.assertIsInstance(lowercase_       ,				lowercase_					)
																			snake_case_									=				np.array(
																			    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
																			snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=1					)
																			self.assertTrue(out is not None					)


				def   A_ (		self    :					int					):
									snake_case_									=				1
									snake_case_									=				self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_					)
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_			,snake_case_			,snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=lowercase_					)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertEqual(len(lowercase_					)       ,				2					)
									self.assertEqual(sorted(doc_dicts[0]					)       ,				['''embeddings''', '''id''', '''text''', '''title''']					)
									self.assertEqual(len(doc_dicts[0]['''id''']					)       ,				lowercase_					)
									self.assertEqual(doc_dicts[0]['''id'''][0]       ,				'''1'''					)  # max inner product is reached with second doc
									self.assertEqual(doc_dicts[1]['''id'''][0]       ,				'''0'''					)  # max inner product is reached with first doc
									self.assertListEqual(doc_ids.tolist()       ,				[[1], [0]]					)


				def   A_ (		self    :					int					):
									snake_case_									=				self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_					)
									with tempfile.TemporaryDirectory() as tmp_dirname:
														retriever.save_pretrained(lowercase_					)
														snake_case_									=				RagRetriever.from_pretrained(lowercase_					)
														self.assertIsInstance(lowercase_       ,				lowercase_					)
														snake_case_									=				np.array(
														    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
														snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=1					)
														self.assertTrue(out is not None					)


				def   A_ (		self    :					str					):
									snake_case_									=				1
									snake_case_									=				self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_					)
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_			,snake_case_			,snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=lowercase_					)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertEqual(len(lowercase_					)       ,				2					)
									self.assertEqual(sorted(doc_dicts[0]					)       ,				['''embeddings''', '''id''', '''text''', '''title''']					)
									self.assertEqual(len(doc_dicts[0]['''id''']					)       ,				lowercase_					)
									self.assertEqual(doc_dicts[0]['''id'''][0]       ,				'''1'''					)  # max inner product is reached with second doc
									self.assertEqual(doc_dicts[1]['''id'''][0]       ,				'''0'''					)  # max inner product is reached with first doc
									self.assertListEqual(doc_ids.tolist()       ,				[[1], [0]]					)


				def   A_ (		self    :					Any					):
									snake_case_									=				self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_					)
									with tempfile.TemporaryDirectory() as tmp_dirname:
														retriever.save_pretrained(lowercase_					)
														snake_case_									=				RagRetriever.from_pretrained(lowercase_					)
														self.assertIsInstance(lowercase_       ,				lowercase_					)
														snake_case_									=				np.array(
														    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
														snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=1					)
														self.assertTrue(out is not None					)


				def   A_ (		self    :					Any					):
									snake_case_									=				1
									snake_case_									=				self.get_dummy_legacy_index_retriever()
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_			,snake_case_			,snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=lowercase_					)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertEqual(len(lowercase_					)       ,				2					)
									self.assertEqual(sorted(doc_dicts[0]					)       ,				['''text''', '''title''']					)
									self.assertEqual(len(doc_dicts[0]['''text''']					)       ,				lowercase_					)
									self.assertEqual(doc_dicts[0]['''text'''][0]       ,				'''bar'''					)  # max inner product is reached with second doc
									self.assertEqual(doc_dicts[1]['''text'''][0]       ,				'''foo'''					)  # max inner product is reached with first doc
									self.assertListEqual(doc_ids.tolist()       ,				[[1], [0]]					)


				def   A_ (		self    :					int					):
									snake_case_									=				self.get_dummy_legacy_index_retriever()
									with tempfile.TemporaryDirectory() as tmp_dirname:
														retriever.save_pretrained(lowercase_					)
														snake_case_									=				RagRetriever.from_pretrained(lowercase_					)
														self.assertIsInstance(lowercase_       ,				lowercase_					)
														snake_case_									=				np.array(
														    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
														snake_case_									=				retriever.retrieve(lowercase_       ,				n_docs=1					)
														self.assertTrue(out is not None					)


				@require_torch
				@require_tokenizers
				@require_sentencepiece
				def   A_ (		self    :					List[str]					):
									import torch

									snake_case_									=				1
									snake_case_									=				self.get_dummy_canonical_hf_index_retriever()
									snake_case_									=				[[5, 7], [10, 11]]
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_									=				retriever(lowercase_       ,				lowercase_       ,				prefix=retriever.config.generator.prefix       ,				n_docs=lowercase_					)
									snake_case_			,snake_case_			,snake_case_									=				(
									    out['''context_input_ids'''],
									    out['''context_attention_mask'''],
									    out['''retrieved_doc_embeds'''],
									)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertIsInstance(lowercase_       ,				lowercase_					)
									self.assertIsInstance(lowercase_       ,				lowercase_					)
									self.assertIsInstance(lowercase_       ,				np.ndarray					)

									snake_case_									=				retriever(
									    lowercase_       ,				lowercase_       ,				prefix=retriever.config.generator.prefix       ,				n_docs=lowercase_       ,				return_tensors='''pt'''       ,				)
									snake_case_			,snake_case_			,snake_case_			,snake_case_									=				(  # noqa: F841
									    out['''context_input_ids'''],
									    out['''context_attention_mask'''],
									    out['''retrieved_doc_embeds'''],
									    out['''doc_ids'''],
									)
									self.assertEqual(retrieved_doc_embeds.shape       ,				(2, n_docs, self.retrieval_vector_size)					)
									self.assertIsInstance(lowercase_       ,				torch.Tensor					)
									self.assertIsInstance(lowercase_       ,				torch.Tensor					)
									self.assertIsInstance(lowercase_       ,				torch.Tensor					)


				@require_torch
				@require_tokenizers
				@require_sentencepiece
				def   A_ (		self    :					Tuple					):
									snake_case_									=				self.get_dpr_ctx_encoder_tokenizer()
									snake_case_									=				1
									snake_case_									=				self.get_dummy_custom_hf_index_retriever(from_disk=lowercase_					)
									retriever.set_ctx_encoder_tokenizer(lowercase_					)

									snake_case_									=				[[5, 7], [10, 11]]
									snake_case_									=				np.array(
									    [np.ones(self.retrieval_vector_size					), -np.ones(self.retrieval_vector_size					)]       ,				dtype=np.floataa					)
									snake_case_									=				retriever(lowercase_       ,				lowercase_       ,				prefix=retriever.config.generator.prefix       ,				n_docs=lowercase_					)

									self.assertEqual(
									    len(lowercase_					)       ,				6					)  # check whether the retriever output consist of 6 attributes including tokenized docs
									self.assertEqual(
									    all(k in out for k in ('''tokenized_doc_ids''', '''tokenized_doc_attention_mask''')					)       ,				lowercase_					)  # check for doc token related keys in dictionary.

