

"""simple docstring"""


import gc
import importlib.metadata
import tempfile
import unittest

from packaging import version

from transformers import (
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    BitsAndBytesConfig,
    pipeline,
)
from transformers.testing_utils import (
    is_torch_available,
    require_accelerate,
    require_bitsandbytes,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)






def     a__    (    __SCREAMING_SNAKE_CASE )	->	Any:
		if model.config.model_type == "gpt2":
				return model.transformer.h[0].mlp.c_fc
		return model.transformer.h[0].mlp.dense_ah_to_h


if is_torch_available():
			import torch
			import torch.nn as nn





			class     snake_case	(				nn.Module  ):

							def __init__(	self							:				Any     ,  UpperCamelCase__							:				nn.Module     ,  UpperCamelCase__							:				int)->   List[Any]:



									'''simple docstring'''


									super().__init__()
									__lowerCAmelCase:       List[Any]          =			module
									__lowerCAmelCase:       Union[str, Any]          =			nn.Sequential(
									    nn.Linear(module.in_features     ,  UpperCamelCase__     ,  bias=UpperCamelCase__)     ,  nn.Linear(UpperCamelCase__     ,  module.out_features     ,  bias=UpperCamelCase__)     ,  )
									__lowerCAmelCase:       List[Any]          =			(2.0 / (5 * min(module.in_features     ,  module.out_features))) ** 0.5
									nn.init.normal_(self.adapter[0].weight     ,  std=UpperCamelCase__)
									nn.init.zeros_(self.adapter[1].weight)
									self.adapter.to(module.weight.device)




							def 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				Dict     ,  *UpperCamelCase__							:				Union[str, Any]     ,  **UpperCamelCase__							:				Optional[Any])->   Union[str, Any]:



									'''simple docstring'''


									return self.module(UpperCamelCase__     ,  *UpperCamelCase__     ,  **UpperCamelCase__) + self.adapter(UpperCamelCase__)





@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class     snake_case	(				unittest.TestCase  ):
				# We keep the constants inside the init function and model loading inside setUp function

				# We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected)
				# Therefore here we use only bloom-1b3 to test our module
				SCREAMING_SNAKE_CASE_   :      Union[str, Any]         =  '''bigscience/bloom-1b7'''

				# Constant values
				SCREAMING_SNAKE_CASE_   :      Tuple         =  2.109_6595_5269_2574

				SCREAMING_SNAKE_CASE_   :      List[str]         =  '''Hello my name is'''
				SCREAMING_SNAKE_CASE_   :      int         =  set()
				EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I"""  )
				EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n"""  )
				EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University"""  )
				SCREAMING_SNAKE_CASE_   :      Dict         =  10

				def 							lowercase_     (	self							:				int)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			AutoTokenizer.from_pretrained(self.model_name)





class     snake_case	(				A__  ):

				def 							lowercase_     (	self							:				List[str])->   List[Any]:



						'''simple docstring'''


						super().setUp()

						# Models and tokenizer
						__lowerCAmelCase:       Tuple          =			AutoModelForCausalLM.from_pretrained(
						    self.model_name     ,  torch_dtype=torch.floataa     ,  device_map="auto")
						__lowerCAmelCase:       List[str]          =			AutoModelForCausalLM.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")

				def 							lowercase_     (	self							:				Optional[int])->   str:



						'''simple docstring'''


						del self.model_fpaa
						del self.model_abit

						gc.collect()
						torch.cuda.empty_cache()

				def 							lowercase_     (	self							:				str)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			self.model_abit.config

						self.assertTrue(hasattr(UpperCamelCase__     ,  "quantization_config"))

						__lowerCAmelCase:       int          =			config.to_dict()
						__lowerCAmelCase:       Union[str, Any]          =			config.to_diff_dict()

						__lowerCAmelCase:       List[Any]          =			config.to_json_string()

				def 							lowercase_     (	self							:				List[str])->   Union[str, Any]:



						'''simple docstring'''


						from bitsandbytes.nn import Paramsabit

						__lowerCAmelCase:       Optional[Any]          =			self.model_fpaa.get_memory_footprint()
						__lowerCAmelCase:       Optional[int]          =			self.model_abit.get_memory_footprint()

						self.assertAlmostEqual(mem_fpaa / mem_abit     ,  self.EXPECTED_RELATIVE_DIFFERENCE)
						__lowerCAmelCase:       Union[str, Any]          =			get_some_linear_layer(self.model_abit)
						self.assertTrue(linear.weight.__class__ == Paramsabit)

				def 							lowercase_     (	self							:				str)->   Tuple:



						'''simple docstring'''


						from transformers import TaPreTrainedModel

						self.model_fpaa.get_memory_footprint()
						self.model_abit.get_memory_footprint()

						for name, module in self.model_abit.named_modules():
								if isinstance(UpperCamelCase__     ,  torch.nn.Linear):
										if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
												# 4-bit parameters are packed in uint8 variables
												self.assertTrue(module.weight.dtype == torch.uinta)

				def 							lowercase_     (	self							:				int)->   List[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.tokenizer(self.input_text     ,  return_tensors="pt")
						__lowerCAmelCase:       Dict          =			self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0)     ,  max_new_tokens=1_0)

						self.assertIn(self.tokenizer.decode(output_sequences[0]     ,  skip_special_tokens=UpperCamelCase__)     ,  self.EXPECTED_OUTPUTS)

				def 							lowercase_     (	self							:				Tuple)->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			BitsAndBytesConfig()
						__lowerCAmelCase:       Tuple          =			True

						__lowerCAmelCase:       Optional[Any]          =			AutoModelForCausalLM.from_pretrained(
						    self.model_name     ,  quantization_config=UpperCamelCase__     ,  device_map="auto")

						__lowerCAmelCase:       str          =			self.tokenizer(self.input_text     ,  return_tensors="pt")
						__lowerCAmelCase:       Tuple          =			model_abit_from_config.generate(
						    input_ids=encoded_input["input_ids"].to(0)     ,  max_new_tokens=1_0)

						self.assertIn(self.tokenizer.decode(output_sequences[0]     ,  skip_special_tokens=UpperCamelCase__)     ,  self.EXPECTED_OUTPUTS)

				def 							lowercase_     (	self							:				List[Any])->   int:



						'''simple docstring'''


						with self.assertRaises(UpperCamelCase__), tempfile.TemporaryDirectory() as tmpdirname:
								self.model_abit.save_pretrained(UpperCamelCase__)

				def 							lowercase_     (	self							:				List[Any])->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			BitsAndBytesConfig()

						with self.assertRaises(UpperCamelCase__):
								__lowerCAmelCase:       int          =			AutoModelForCausalLM.from_pretrained(
								    self.model_name     ,  quantization_config=UpperCamelCase__     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto"     ,  bnb_abit_quant_type="nf4"     ,  )

				def 							lowercase_     (	self							:				int)->   Union[str, Any]:



						'''simple docstring'''


						with self.assertRaises(UpperCamelCase__):
								# Tries with `str`
								self.model_abit.to("cpu")

						with self.assertRaises(UpperCamelCase__):
								# Tries with a `dtype``
								self.model_abit.to(torch.floataa)

						with self.assertRaises(UpperCamelCase__):
								# Tries with a `device`
								self.model_abit.to(torch.device("cuda:0"))

						with self.assertRaises(UpperCamelCase__):
								# Tries with a `device`
								self.model_abit.float()

						with self.assertRaises(UpperCamelCase__):
								# Tries with a `device`
								self.model_abit.half()

						# Test if we did not break anything
						__lowerCAmelCase:       Any          =			self.tokenizer(self.input_text     ,  return_tensors="pt")

						__lowerCAmelCase:       int          =			self.model_fpaa.to(torch.floataa)
						__lowerCAmelCase:       Optional[int]          =			self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0)     ,  max_new_tokens=1_0)

						# Check this does not throw an error
						__lowerCAmelCase:       Optional[int]          =			self.model_fpaa.to("cpu")

						# Check this does not throw an error
						__lowerCAmelCase:       List[Any]          =			self.model_fpaa.half()

						# Check this does not throw an error
						__lowerCAmelCase:       Optional[Any]          =			self.model_fpaa.float()




				def 							lowercase_     (	self							:				Tuple)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			AutoModelForSeqaSeqLM.from_pretrained("t5-small"     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa)





@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class     snake_case	(				unittest.TestCase  ):

				@classmethod
				def 							lowercase_     (	cls							:				Optional[int])->   int:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			"t5-small"
						__lowerCAmelCase:       Optional[Any]          =			"google/flan-t5-small"  # flan-t5 uses dense-act instead of dense-relu-dense
						__lowerCAmelCase:       Union[str, Any]          =			AutoTokenizer.from_pretrained(cls.model_name)
						__lowerCAmelCase:       Any          =			"Translate in German: Hello, my dog is cute"

				def 							lowercase_     (	self							:				Tuple)->   Optional[Any]:



						'''simple docstring'''


						gc.collect()
						torch.cuda.empty_cache()

				def 							lowercase_     (	self							:				Dict)->   int:



						'''simple docstring'''


						from transformers import TaForConditionalGeneration

						__lowerCAmelCase:       int          =			TaForConditionalGeneration._keep_in_fpaa_modules
						__lowerCAmelCase:       int          =			None

						# test with `t5-small`
						__lowerCAmelCase:       List[Any]          =			TaForConditionalGeneration.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						__lowerCAmelCase:       int          =			self.tokenizer(self.input_text     ,  return_tensors="pt").to(0)
						__lowerCAmelCase:       Any          =			model.generate(**UpperCamelCase__)

						# test with `flan-t5-small`
						__lowerCAmelCase:       str          =			TaForConditionalGeneration.from_pretrained(
						    self.dense_act_model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						__lowerCAmelCase:       int          =			self.tokenizer(self.input_text     ,  return_tensors="pt").to(0)
						__lowerCAmelCase:       Union[str, Any]          =			model.generate(**UpperCamelCase__)
						__lowerCAmelCase:       Tuple          =			modules




				def 							lowercase_     (	self							:				List[Any])->   List[str]:



						'''simple docstring'''


						import bitsandbytes as bnb

						from transformers import TaForConditionalGeneration

						# test with `t5-small`
						__lowerCAmelCase:       List[str]          =			TaForConditionalGeneration.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")

						# there was a bug with decoders - this test checks that it is fixed
						self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q     ,  bnb.nn.Linearabit))

						__lowerCAmelCase:       Union[str, Any]          =			self.tokenizer(self.input_text     ,  return_tensors="pt").to(0)
						__lowerCAmelCase:       Optional[int]          =			model.generate(**UpperCamelCase__)

						# test with `flan-t5-small`
						__lowerCAmelCase:       Union[str, Any]          =			TaForConditionalGeneration.from_pretrained(
						    self.dense_act_model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						__lowerCAmelCase:       Tuple          =			self.tokenizer(self.input_text     ,  return_tensors="pt").to(0)
						__lowerCAmelCase:       str          =			model.generate(**UpperCamelCase__)





class     snake_case	(				A__  ):

				def 							lowercase_     (	self							:				Tuple)->   List[str]:



						'''simple docstring'''


						super().setUp()
						# model_name
						__lowerCAmelCase:       Any          =			"bigscience/bloom-560m"
						__lowerCAmelCase:       List[str]          =			"t5-small"

						# Different types of model

						__lowerCAmelCase:       List[Any]          =			AutoModel.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						# Sequence classification model
						__lowerCAmelCase:       Tuple          =			AutoModelForSequenceClassification.from_pretrained(
						    self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						# CausalLM model
						__lowerCAmelCase:       List[str]          =			AutoModelForCausalLM.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")
						# Seq2seq model
						__lowerCAmelCase:       Dict          =			AutoModelForSeqaSeqLM.from_pretrained(
						    self.seq_to_seq_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="auto")

				def 							lowercase_     (	self							:				Union[str, Any])->   Optional[int]:



						'''simple docstring'''


						del self.base_model
						del self.sequence_model
						del self.model_abit
						del self.seq_to_seq_model

						gc.collect()
						torch.cuda.empty_cache()




				def 							lowercase_     (	self							:				Optional[Any])->   Union[str, Any]:



						'''simple docstring'''


						from bitsandbytes.nn import Paramsabit

						self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit)

						# Other heads should be nn.Parameter
						self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter)
						self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter)
						self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter)





class     snake_case	(				A__  ):

				def 							lowercase_     (	self							:				Optional[int])->   Dict:



						'''simple docstring'''


						super().setUp()

				def 							lowercase_     (	self							:				Optional[int])->   Optional[Any]:



						'''simple docstring'''


						del self.pipe

						gc.collect()
						torch.cuda.empty_cache()




				def 							lowercase_     (	self							:				Optional[int])->   int:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			pipeline(
						    "text-generation"     ,  model=self.model_name     ,  model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa}     ,  max_new_tokens=self.MAX_NEW_TOKENS     ,  )

						# Real second forward pass
						__lowerCAmelCase:       int          =			self.pipe(self.input_text)
						self.assertIn(pipeline_output[0]["generated_text"]     ,  self.EXPECTED_OUTPUTS)





@require_torch_multi_gpu
class     snake_case	(				A__  ):

				def 							lowercase_     (	self							:				Union[str, Any])->   Dict:



						'''simple docstring'''


						super().setUp()




				def 							lowercase_     (	self							:				str)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			AutoModelForCausalLM.from_pretrained(
						    self.model_name     ,  load_in_abit=UpperCamelCase__     ,  device_map="balanced")

						# Check correct device map
						self.assertEqual(set(model_parallel.hf_device_map.values())     ,  {0, 1})

						# Check that inference pass works on the model
						__lowerCAmelCase:       Optional[Any]          =			self.tokenizer(self.input_text     ,  return_tensors="pt")

						# Second real batch
						__lowerCAmelCase:       Any          =			model_parallel.generate(input_ids=encoded_input["input_ids"].to(0)     ,  max_new_tokens=1_0)
						self.assertIn(self.tokenizer.decode(output_parallel[0]     ,  skip_special_tokens=UpperCamelCase__)     ,  self.EXPECTED_OUTPUTS)





class     snake_case	(				A__  ):

				def 							lowercase_     (	self							:				str)->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			"facebook/opt-350m"
						super().setUp()




				def 							lowercase_     (	self							:				List[str])->   List[str]:



						'''simple docstring'''


						if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"):
								return

						# Step 1: freeze all parameters
						__lowerCAmelCase:       str          =			AutoModelForCausalLM.from_pretrained(self.model_name     ,  load_in_abit=UpperCamelCase__)

						self.assertEqual(set(model.hf_device_map.values())     ,  {torch.cuda.current_device()})

						for param in model.parameters():
								__lowerCAmelCase:       Optional[int]          =			False  # freeze the model - train adapters later
								if param.ndim == 1:
										# cast the small parameters (e.g. layernorm) to fp32 for stability
										__lowerCAmelCase:       List[Any]          =			param.data.to(torch.floataa)

        # Step 2: add adapters
						for _, module in model.named_modules():
								if "OPTAttention" in repr(type(UpperCamelCase__)):
										__lowerCAmelCase:       int          =			LoRALayer(module.q_proj     ,  rank=1_6)
										__lowerCAmelCase:       List[Any]          =			LoRALayer(module.k_proj     ,  rank=1_6)
										__lowerCAmelCase:       List[str]          =			LoRALayer(module.v_proj     ,  rank=1_6)

        # Step 3: dummy batch
						__lowerCAmelCase:       int          =			self.tokenizer("Test batch "     ,  return_tensors="pt").to(0)

						# Step 4: Check if the gradient is not None
						with torch.cuda.amp.autocast():
								__lowerCAmelCase:       str          =			model.forward(**UpperCamelCase__)
								out.logits.norm().backward()

						for module in model.modules():
								if isinstance(UpperCamelCase__     ,  UpperCamelCase__):
										self.assertTrue(module.adapter[1].weight.grad is not None)
										self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0)
								elif isinstance(UpperCamelCase__     ,  nn.Embedding):
										self.assertTrue(module.weight.grad is None)





class     snake_case	(				A__  ):
				SCREAMING_SNAKE_CASE_   :      Any         =  '''gpt2-xl'''
				SCREAMING_SNAKE_CASE_   :      Union[str, Any]         =  3.3191_8548_5415_2187










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  (    A__       ):







 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






      UpperCamelCase__			:   List[str]       				=  tempfile.mkdtemp()
      UpperCamelCase__			:   Any       				=  8

      # DPR tok
      UpperCamelCase__			:   List[Any]       				=  [
          "[UNK]",
          "[CLS]",
          "[SEP]",
          "[PAD]",
          "[MASK]",
          "want",
          "##want",
          "##ed",
          "wa",
          "un",
          "runn",
          "##ing",
          ",",
          "low",
          "lowest",
      ]
      UpperCamelCase__			:   Any       				=  os.path.join(self.tmpdirname							,   "dpr_tokenizer"						)
      os.makedirs(SCREAMING_SNAKE_CASE							,   exist_ok=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Optional[int]       				=  os.path.join(SCREAMING_SNAKE_CASE							,   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
      UpperCamelCase__			:   str       				=  [
          "l",
          "o",
          "w",
          "e",
          "r",
          "s",
          "t",
          "i",
          "d",
          "n",
          "\u0120",
          "\u0120l",
          "\u0120n",
          "\u0120lo",
          "\u0120low",
          "er",
          "\u0120lowest",
          "\u0120newer",
          "\u0120wider",
          "<unk>",
      ]
      UpperCamelCase__			:   int       				=  dict(zip(SCREAMING_SNAKE_CASE							,   range(len(SCREAMING_SNAKE_CASE						)						)						)						)
      UpperCamelCase__			:   Optional[Any]       				=  ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
      UpperCamelCase__			:   Union[str, Any]       				=  {"unk_token": "<unk>"}

      UpperCamelCase__			:   Dict       				=  os.path.join(self.tmpdirname							,   "bart_tokenizer"						)
      os.makedirs(SCREAMING_SNAKE_CASE							,   exist_ok=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   List[str]       				=  os.path.join(SCREAMING_SNAKE_CASE							,   BART_VOCAB_FILES_NAMES["vocab_file"]						)
      UpperCamelCase__			:   str       				=  os.path.join(SCREAMING_SNAKE_CASE							,   BART_VOCAB_FILES_NAMES["merges_file"]						)
      with open(self.vocab_file							,   "w"							,   encoding="utf-8"						) as fp:
           fp.write(json.dumps(SCREAMING_SNAKE_CASE						) + "\n"						)
      with open(self.merges_file							,   "w"							,   encoding="utf-8"						) as fp:
           fp.write("\n".join(SCREAMING_SNAKE_CASE						)						)







 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname							,   "dpr_tokenizer"						)						)







 def 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname							,   "dpr_tokenizer"						)						)







 def 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname							,   "bart_tokenizer"						)						)







 def 					__lowercase					(		self					:   Optional[Any]						):


      '''simple docstring'''






      shutil.rmtree(self.tmpdirname						)







 def 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__			:   Tuple       				=  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 					__lowercase					(		self					:   Optional[int]						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  self.get_dummy_dataset()
      UpperCamelCase__			:   List[Any]       				=  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:
           UpperCamelCase__			:   str       				=  dataset
           UpperCamelCase__			:   Optional[int]       				=  RagRetriever(
               SCREAMING_SNAKE_CASE							,   question_encoder_tokenizer=self.get_dpr_tokenizer()							,   generator_tokenizer=self.get_bart_tokenizer()							,   )
      return retriever







 def 					__lowercase					(		self					:   int							,   SCREAMING_SNAKE_CASE					:   bool						):


      '''simple docstring'''






      UpperCamelCase__			:   Dict       				=  self.get_dummy_dataset()
      UpperCamelCase__			:   Tuple       				=  RagConfig(
          retrieval_vector_size=self.retrieval_vector_size							,   question_encoder=DPRConfig().to_dict()							,   generator=BartConfig().to_dict()							,   index_name="custom"							,   )
      if from_disk:
           UpperCamelCase__			:   Optional[int]       				=  os.path.join(self.tmpdirname							,   "dataset"						)
           UpperCamelCase__			:   List[str]       				=  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
           UpperCamelCase__			:   str       				=  RagRetriever(
               SCREAMING_SNAKE_CASE							,   question_encoder_tokenizer=self.get_dpr_tokenizer()							,   generator_tokenizer=self.get_bart_tokenizer()							,   )
      else:
           UpperCamelCase__			:   List[Any]       				=  RagRetriever(
               SCREAMING_SNAKE_CASE							,   question_encoder_tokenizer=self.get_dpr_tokenizer()							,   generator_tokenizer=self.get_bart_tokenizer()							,   index=CustomHFIndex(config.retrieval_vector_size							,   SCREAMING_SNAKE_CASE						)							,   )
      return retriever







 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  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						)

      UpperCamelCase__			:   List[str]       				=  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"						)						)

      UpperCamelCase__			:   Optional[int]       				=  os.path.join(self.tmpdirname							,   "psgs_w100.tsv.pkl"						)
      UpperCamelCase__			:   Tuple       				=  {sample["id"]: [sample["text"], sample["title"]] for sample in dataset}
      pickle.dump(SCREAMING_SNAKE_CASE							,   open(SCREAMING_SNAKE_CASE							,   "wb"						)						)

      UpperCamelCase__			:   List[str]       				=  RagConfig(
          retrieval_vector_size=self.retrieval_vector_size							,   question_encoder=DPRConfig().to_dict()							,   generator=BartConfig().to_dict()							,   index_name="legacy"							,   index_path=self.tmpdirname							,   )
      UpperCamelCase__			:   List[str]       				=  RagRetriever(
          SCREAMING_SNAKE_CASE							,   question_encoder_tokenizer=self.get_dpr_tokenizer()							,   generator_tokenizer=self.get_bart_tokenizer()						)
      return retriever







 def 					__lowercase					(		self					:   Optional[Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Union[str, Any]       				=  1
      UpperCamelCase__			:   Tuple       				=  self.get_dummy_canonical_hf_index_retriever()
      UpperCamelCase__			:   str       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   List[str]       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=SCREAMING_SNAKE_CASE						)
      self.assertEqual(retrieved_doc_embeds.shape							,   (2, n_docs, self.retrieval_vector_size)						)
      self.assertEqual(len(SCREAMING_SNAKE_CASE						)							,   2						)
      self.assertEqual(sorted(doc_dicts[0]						)							,   ["embeddings", "id", "text", "title"]						)
      self.assertEqual(len(doc_dicts[0]["id"]						)							,   SCREAMING_SNAKE_CASE						)
      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 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  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:
                UpperCamelCase__			:   Optional[int]       				=  self.get_dummy_dataset()
                retriever.save_pretrained(SCREAMING_SNAKE_CASE						)
                UpperCamelCase__			:   Any       				=  RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE						)
                self.assertIsInstance(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)
                UpperCamelCase__			:   str       				=  np.array(
                    [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
                UpperCamelCase__			:   Any       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=1						)
                self.assertTrue(out is not None						)







 def 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  1
      UpperCamelCase__			:   Dict       				=  self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Tuple       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   List[str]       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=SCREAMING_SNAKE_CASE						)
      self.assertEqual(retrieved_doc_embeds.shape							,   (2, n_docs, self.retrieval_vector_size)						)
      self.assertEqual(len(SCREAMING_SNAKE_CASE						)							,   2						)
      self.assertEqual(sorted(doc_dicts[0]						)							,   ["embeddings", "id", "text", "title"]						)
      self.assertEqual(len(doc_dicts[0]["id"]						)							,   SCREAMING_SNAKE_CASE						)
      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 					__lowercase					(		self					:   str						):


      '''simple docstring'''






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







 def 					__lowercase					(		self					:   List[str]						):


      '''simple docstring'''






      UpperCamelCase__			:   int       				=  1
      UpperCamelCase__			:   List[str]       				=  self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__			:   Dict       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   List[str]       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=SCREAMING_SNAKE_CASE						)
      self.assertEqual(retrieved_doc_embeds.shape							,   (2, n_docs, self.retrieval_vector_size)						)
      self.assertEqual(len(SCREAMING_SNAKE_CASE						)							,   2						)
      self.assertEqual(sorted(doc_dicts[0]						)							,   ["embeddings", "id", "text", "title"]						)
      self.assertEqual(len(doc_dicts[0]["id"]						)							,   SCREAMING_SNAKE_CASE						)
      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 					__lowercase					(		self					:   Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   List[str]       				=  self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE						)
      with tempfile.TemporaryDirectory() as tmp_dirname:
           retriever.save_pretrained(SCREAMING_SNAKE_CASE						)
           UpperCamelCase__			:   Optional[int]       				=  RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE						)
           self.assertIsInstance(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)
           UpperCamelCase__			:   Dict       				=  np.array(
               [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
           UpperCamelCase__			:   Union[str, Any]       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=1						)
           self.assertTrue(out is not None						)







 def 					__lowercase					(		self					:   Tuple						):


      '''simple docstring'''






      UpperCamelCase__			:   List[str]       				=  1
      UpperCamelCase__			:   Any       				=  self.get_dummy_legacy_index_retriever()
      UpperCamelCase__			:   Optional[int]       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   Tuple       				=  retriever.retrieve(SCREAMING_SNAKE_CASE							,   n_docs=SCREAMING_SNAKE_CASE						)
      self.assertEqual(retrieved_doc_embeds.shape							,   (2, n_docs, self.retrieval_vector_size)						)
      self.assertEqual(len(SCREAMING_SNAKE_CASE						)							,   2						)
      self.assertEqual(sorted(doc_dicts[0]						)							,   ["text", "title"]						)
      self.assertEqual(len(doc_dicts[0]["text"]						)							,   SCREAMING_SNAKE_CASE						)
      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 					__lowercase					(		self					:   List[Any]						):


      '''simple docstring'''






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







 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def 					__lowercase					(		self					:   int						):


      '''simple docstring'''






      import torch

      UpperCamelCase__			:   Optional[Any]       				=  1
      UpperCamelCase__			:   Optional[int]       				=  self.get_dummy_canonical_hf_index_retriever()
      UpperCamelCase__			:   Optional[Any]       				=  [[5, 7], [10, 11]]
      UpperCamelCase__			:   List[str]       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__			:   int       				=  retriever(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   prefix=retriever.config.generator.prefix							,   n_docs=SCREAMING_SNAKE_CASE						)
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   List[str]       				=  (
          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(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)
      self.assertIsInstance(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE						)
      self.assertIsInstance(SCREAMING_SNAKE_CASE							,   np.ndarray						)

      UpperCamelCase__			:   List[Any]       				=  retriever(
          SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   prefix=retriever.config.generator.prefix							,   n_docs=SCREAMING_SNAKE_CASE							,   return_tensors="pt"							,   )
      UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__			:   List[Any]       				=  (  # 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(SCREAMING_SNAKE_CASE							,   torch.Tensor						)
      self.assertIsInstance(SCREAMING_SNAKE_CASE							,   torch.Tensor						)
      self.assertIsInstance(SCREAMING_SNAKE_CASE							,   torch.Tensor						)







 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def 					__lowercase					(		self					:   Union[str, Any]						):


      '''simple docstring'''






      UpperCamelCase__			:   Optional[int]       				=  self.get_dpr_ctx_encoder_tokenizer()
      UpperCamelCase__			:   Union[str, Any]       				=  1
      UpperCamelCase__			:   Tuple       				=  self.get_dummy_custom_hf_index_retriever(from_disk=SCREAMING_SNAKE_CASE						)
      retriever.set_ctx_encoder_tokenizer(SCREAMING_SNAKE_CASE						)

      UpperCamelCase__			:   Tuple       				=  [[5, 7], [10, 11]]
      UpperCamelCase__			:   List[str]       				=  np.array(
          [np.ones(self.retrieval_vector_size						), -np.ones(self.retrieval_vector_size						)]							,   dtype=np.floataa						)
      UpperCamelCase__			:   Optional[int]       				=  retriever(SCREAMING_SNAKE_CASE							,   SCREAMING_SNAKE_CASE							,   prefix=retriever.config.generator.prefix							,   n_docs=SCREAMING_SNAKE_CASE						)

      self.assertEqual(
          len(SCREAMING_SNAKE_CASE						)							,   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")						)							,   SCREAMING_SNAKE_CASE						)  # check for doc token related keys in dictionary.