
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import BlipImageProcessor





class 						__lowercase(     unittest.TestCase   ):


       """simple docstring"""







       def __init__(     self					:			List[Any]  ,      _lowerCAmelCase					:			Optional[int]  ,      _lowerCAmelCase					:			Optional[Any]=7  ,      _lowerCAmelCase					:			List[Any]=3  ,      _lowerCAmelCase					:			Dict=18  ,      _lowerCAmelCase					:			List[Any]=30  ,      _lowerCAmelCase					:			Tuple=400  ,      _lowerCAmelCase					:			Optional[int]=True  ,      _lowerCAmelCase					:			Dict=None  ,      _lowerCAmelCase					:			Dict=True  ,      _lowerCAmelCase					:			List[str]=False  ,      _lowerCAmelCase					:			Dict=[0.48145466, 0.4578275, 0.40821073]  ,      _lowerCAmelCase					:			str=[0.26862954, 0.26130258, 0.27577711]  ,      _lowerCAmelCase					:			Dict=True  ,      )					->   List[Any]:
         _lowerCAmelCase						=		size if size is not None else {'height': 20, 'width': 20}
         _lowerCAmelCase						=		parent
         _lowerCAmelCase						=		batch_size
         _lowerCAmelCase						=		num_channels
         _lowerCAmelCase						=		image_size
         _lowerCAmelCase						=		min_resolution
         _lowerCAmelCase						=		max_resolution
         _lowerCAmelCase						=		do_resize
         _lowerCAmelCase						=		size
         _lowerCAmelCase						=		do_normalize
         _lowerCAmelCase						=		image_mean
         _lowerCAmelCase						=		image_std
         _lowerCAmelCase						=		do_pad
         _lowerCAmelCase						=		do_convert_rgb



       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Dict:
         return {
             "do_resize": self.do_resize,
             "size": self.size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_convert_rgb": self.do_convert_rgb,
             "do_pad": self.do_pad,
         }






       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[int]  ,      _lowerCAmelCase					:			List[Any]=False  ,      _lowerCAmelCase					:			List[str]=False  ,      _lowerCAmelCase					:			Dict=False       )					->   Union[str, Any]:
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
           _lowerCAmelCase						=		[]
           for i in range(self.batch_size       ):
             image_inputs.append(
                 np.random.randint(
                     255  ,      size=(self.num_channels, self.max_resolution, self.max_resolution)  ,      dtype=np.uinta       )       )
         else:
           _lowerCAmelCase						=		[]
           for i in range(self.batch_size       ):
             _lowerCAmelCase	,       _lowerCAmelCase						=		np.random.choice(np.arange(self.min_resolution  ,      self.max_resolution       )  ,      2       )
             image_inputs.append(np.random.randint(255  ,      size=(self.num_channels, width, height)  ,      dtype=np.uinta       )       )

         if not numpify and not torchify:
           # PIL expects the channel dimension as last dimension
           _lowerCAmelCase						=		[Image.fromarray(np.moveaxis(_lowerCAmelCase  ,      0  ,      -1       )       ) for x in image_inputs]

         if torchify:
           _lowerCAmelCase						=		[torch.from_numpy(_lowerCAmelCase       ) for x in image_inputs]

         return image_inputs





@require_torch
@require_vision
class 						__lowercase(     SCREAMING_SNAKE_CASE		,  unittest.TestCase   ):


       """simple docstring"""







       UpperCamelCase_				 =							BlipImageProcessor if is_vision_available() else None



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   Optional[int]:
         _lowerCAmelCase						=		BlipImageProcessingTester(self       )



       @property
       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[int]       )					->   Tuple:
         return self.image_processor_tester.prepare_image_processor_dict()



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   int:
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_resize'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'size'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_normalize'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'image_mean'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'image_std'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_convert_rgb'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]       )					->   List[Any]:
         pass



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   int:
         # Initialize image_processor
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         # create random PIL images
         _lowerCAmelCase						=		self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCAmelCase       )
         for image in image_inputs:
           self.assertIsInstance(_lowerCAmelCase  ,      Image.Image       )

         # Test not batched input
         _lowerCAmelCase						=		image_processor(image_inputs[0]  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )

         # Test batched
         _lowerCAmelCase						=		image_processor(_lowerCAmelCase  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )



       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]       )					->   Dict:
         # Initialize image_processor
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         # create random numpy tensors
         _lowerCAmelCase						=		self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCAmelCase  ,      numpify=_lowerCAmelCase       )
         for image in image_inputs:
           self.assertIsInstance(_lowerCAmelCase  ,      np.ndarray       )

         # Test not batched input
         _lowerCAmelCase						=		image_processor(image_inputs[0]  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )

         # Test batched
         _lowerCAmelCase						=		image_processor(_lowerCAmelCase  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )






       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]       )					->   str:
         # Initialize image_processor
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         # create random PyTorch tensors
         _lowerCAmelCase						=		self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCAmelCase  ,      torchify=_lowerCAmelCase       )
         for image in image_inputs:
           self.assertIsInstance(_lowerCAmelCase  ,      torch.Tensor       )

         # Test not batched input
         _lowerCAmelCase						=		image_processor(image_inputs[0]  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )

         # Test batched
         _lowerCAmelCase						=		image_processor(_lowerCAmelCase  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )





@require_torch
@require_vision
class 						__lowercase(     SCREAMING_SNAKE_CASE		,  unittest.TestCase   ):


       """simple docstring"""







       UpperCamelCase_				 =							BlipImageProcessor if is_vision_available() else None



       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   str:
         _lowerCAmelCase						=		BlipImageProcessingTester(self  ,      num_channels=4       )
         _lowerCAmelCase						=		3



       @property
       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]       )					->   Any:
         return self.image_processor_tester.prepare_image_processor_dict()



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   Tuple:
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_resize'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'size'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_normalize'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'image_mean'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'image_std'       )       )
         self.assertTrue(hasattr(_lowerCAmelCase  ,      'do_convert_rgb'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[int]       )					->   List[Any]:
         pass






       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]       )					->   List[str]:
         # Initialize image_processor
         _lowerCAmelCase						=		self.image_processing_class(**self.image_processor_dict       )
         # create random PIL images
         _lowerCAmelCase						=		self.image_processor_tester.prepare_inputs(equal_resolution=_lowerCAmelCase       )
         for image in image_inputs:
           self.assertIsInstance(_lowerCAmelCase  ,      Image.Image       )

         # Test not batched input
         _lowerCAmelCase						=		image_processor(image_inputs[0]  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 1,
                 self.expected_encoded_image_num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )

         # Test batched
         _lowerCAmelCase						=		image_processor(_lowerCAmelCase  ,      return_tensors='pt'       ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,      (
                 self.image_processor_tester.batch_size,
                 self.expected_encoded_image_num_channels,
                 self.image_processor_tester.size['height'],
                 self.image_processor_tester.size['width'],
             )  ,      )


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

import faiss
import numpy as np
from datasets import Dataset

from transformers import BartConfig, BartTokenizer, DPRConfig, DPRQuestionEncoderTokenizer, RagConfig
from transformers.file_utils import is_datasets_available, is_faiss_available, is_psutil_available, is_torch_available
from transformers.integrations import is_ray_available
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
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_ray


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # noqa: E402 # isort:skip

if is_torch_available():
       from distributed_pytorch_retriever import RagPyTorchDistributedRetriever  # noqa: E402 # isort:skip
else:
       _UpperCamelCase:					List[Any]     =None

if is_ray_available():
       import ray  # noqa: E402 # isort:skip
       from distributed_ray_retriever import RagRayDistributedRetriever, RayRetriever  # noqa: E402 # isort:skip
else:
       _UpperCamelCase:					List[str]     =None
       _UpperCamelCase:					Tuple     =None
       _UpperCamelCase:					Any     =None



def 	_a  (					__SCREAMING_SNAKE_CASE					:  Optional[int]    ):






  """simple docstring"""




  if not (is_datasets_available() and is_faiss_available() and is_psutil_available()):
    _lowerCAmelCase						=		unittest.skip('test requires Datasets, Faiss, psutil'    )(__SCREAMING_SNAKE_CASE    )
  return test_case





@require_distributed_retrieval
class 						__lowercase(     SCREAMING_SNAKE_CASE   ):


       """simple docstring"""







       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   Optional[Any]:
         _lowerCAmelCase						=		tempfile.mkdtemp()
         _lowerCAmelCase						=		8

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

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



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   DPRQuestionEncoderTokenizer:
         return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname  ,      'dpr_tokenizer'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Any       )					->   BartTokenizer:
         return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname  ,      'bart_tokenizer'       )       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   int:
         shutil.rmtree(self.tmpdirname       )



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   str:
         _lowerCAmelCase						=		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 SCREAMING_SNAKE_CASE_				(     self					:			int  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			Tuple=1_2345       )					->   RagPyTorchDistributedRetriever:
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		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:
           _lowerCAmelCase						=		dataset
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      )
           if init_retrieval:
             retriever.init_retrieval(_lowerCAmelCase       )
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Any  ,      _lowerCAmelCase					:			bool       )					->   RagRayDistributedRetriever:
         # Have to run in local mode because sys.path modifications at top of
         # file are not propogated to remote workers.
         # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
         ray.init(local_mode=_lowerCAmelCase       )
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      )
         _lowerCAmelCase						=		ray.remote(_lowerCAmelCase       )
         _lowerCAmelCase						=		[remote_cls.remote() for _ in range(1       )]
         with patch('transformers.models.rag.retrieval_rag.load_dataset'       ) as mock_load_dataset:
           _lowerCAmelCase						=		self.get_dummy_dataset()
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      )
           if init_retrieval:
             retriever.init_retrieval()
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			List[Any]=1_2345       )					->   List[Any]:
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      index_name='custom'  ,      )
         if from_disk:
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'dataset'       )
           _lowerCAmelCase						=		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
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      )
         else:
           _lowerCAmelCase						=		RagPyTorchDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      index=CustomHFIndex(config.retrieval_vector_size  ,      _lowerCAmelCase       )  ,      )
         if init_retrieval:
           retriever.init_retrieval(_lowerCAmelCase       )
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]  ,      _lowerCAmelCase					:			bool  ,      _lowerCAmelCase					:			bool       )					->   int:
         # Have to run in local mode because sys.path modifications at top of
         # file are not propogated to remote workers.
         # https://stackoverflow.com/questions/54338013/parallel-import-a-python-file-from-sibling-folder
         ray.init(local_mode=_lowerCAmelCase       )
         _lowerCAmelCase						=		self.get_dummy_dataset()
         _lowerCAmelCase						=		RagConfig(
             retrieval_vector_size=self.retrieval_vector_size  ,      question_encoder=DPRConfig().to_dict()  ,      generator=BartConfig().to_dict()  ,      index_name='custom'  ,      )
         _lowerCAmelCase						=		ray.remote(_lowerCAmelCase       )
         _lowerCAmelCase						=		[remote_cls.remote() for _ in range(1       )]
         if from_disk:
           _lowerCAmelCase						=		os.path.join(self.tmpdirname  ,      'dataset'       )
           _lowerCAmelCase						=		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
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      index=CustomHFIndex.load_from_disk(
                   vector_size=config.retrieval_vector_size  ,      dataset_path=config.passages_path  ,      index_path=config.index_path  ,      )  ,      )
         else:
           _lowerCAmelCase						=		RagRayDistributedRetriever(
               _lowerCAmelCase  ,      question_encoder_tokenizer=self.get_dpr_tokenizer()  ,      generator_tokenizer=self.get_bart_tokenizer()  ,      retrieval_workers=_lowerCAmelCase  ,      index=CustomHFIndex(config.retrieval_vector_size  ,      _lowerCAmelCase       )  ,      )
         if init_retrieval:
           retriever.init_retrieval()
         return retriever



       def SCREAMING_SNAKE_CASE_				(     self					:			str  ,      _lowerCAmelCase					:			RagRetriever  ,      _lowerCAmelCase					:			np.array  ,      _lowerCAmelCase					:			int       )					->   None:
         _lowerCAmelCase	,       _lowerCAmelCase	,       _lowerCAmelCase						=		retriever.retrieve(_lowerCAmelCase  ,      n_docs=_lowerCAmelCase       )
         self.assertEqual(retrieved_doc_embeds.shape  ,      (2, n_docs, self.retrieval_vector_size)       )
         self.assertEqual(len(_lowerCAmelCase       )  ,      2       )
         self.assertEqual(sorted(doc_dicts[0]       )  ,      ['embeddings', 'id', 'text', 'title']       )
         self.assertEqual(len(doc_dicts[0]['id']       )  ,      _lowerCAmelCase       )
         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 SCREAMING_SNAKE_CASE_				(     self					:			Any       )					->   Optional[int]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_pytorch_distributed_retriever(init_retrieval=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   Any:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )



       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Optional[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_pytorch_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )



       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Any:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_ray_distributed_retriever(init_retrieval=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )
         ray.shutdown()



       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   Optional[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )
         with self.assertRaises(_lowerCAmelCase       ):
           self.distributed_retriever_check(
               self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      )
         ray.shutdown()






       @require_ray
       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   List[Any]:
         _lowerCAmelCase						=		1
         _lowerCAmelCase						=		np.array(
             [np.ones(self.retrieval_vector_size       ), -np.ones(self.retrieval_vector_size       )]  ,      dtype=np.floataa       )

         self.distributed_retriever_check(
             self.get_dummy_custom_hf_index_ray_retriever(init_retrieval=_lowerCAmelCase  ,      from_disk=_lowerCAmelCase       )  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )
         ray.shutdown()
