
import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 						__lowercase(     SCREAMING_SNAKE_CASE		,  unittest.TestCase   ):


       """simple docstring"""







       UpperCamelCase_				 =							PaintByExamplePipeline
       UpperCamelCase_				 =							IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
       UpperCamelCase_				 =							IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
       UpperCamelCase_				 =							frozenset([]   )  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   str:
         torch.manual_seed(0       )
         _lowerCAmelCase						=		UNetaDConditionModel(
             block_out_channels=(32, 64)  ,      layers_per_block=2  ,      sample_size=32  ,      in_channels=9  ,      out_channels=4  ,      down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,      up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,      cross_attention_dim=32  ,      )
         _lowerCAmelCase						=		PNDMScheduler(skip_prk_steps=_lowerCAmelCase       )
         torch.manual_seed(0       )
         _lowerCAmelCase						=		AutoencoderKL(
             block_out_channels=[32, 64]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=4  ,      )
         torch.manual_seed(0       )
         _lowerCAmelCase						=		CLIPVisionConfig(
             hidden_size=32  ,      projection_dim=32  ,      intermediate_size=37  ,      layer_norm_eps=1e-05  ,      num_attention_heads=4  ,      num_hidden_layers=5  ,      image_size=32  ,      patch_size=4  ,      )
         _lowerCAmelCase						=		PaintByExampleImageEncoder(_lowerCAmelCase  ,      proj_size=32       )
         _lowerCAmelCase						=		CLIPImageProcessor(crop_size=32  ,      size=32       )

         _lowerCAmelCase						=		{
             'unet': unet,
             'scheduler': scheduler,
             'vae': vae,
             'image_encoder': image_encoder,
             'safety_checker': None,
             'feature_extractor': feature_extractor,
         }
         return components



       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]  ,      _lowerCAmelCase					:			Optional[Any]       )					->   Tuple:
         _lowerCAmelCase						=		np.array(image.convert('RGB'       )       )
         _lowerCAmelCase						=		image[None].transpose(0  ,      3  ,      1  ,      2       )
         _lowerCAmelCase						=		torch.from_numpy(_lowerCAmelCase       ).to(dtype=torch.floataa       ) / 127.5 - 1.0
         return image



       def SCREAMING_SNAKE_CASE_				(     self					:			Any  ,      _lowerCAmelCase					:			Tuple="cpu"  ,      _lowerCAmelCase					:			List[str]=0       )					->   str:
         # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
         _lowerCAmelCase						=		floats_tensor((1, 3, 32, 32)  ,      rng=random.Random(_lowerCAmelCase       )       ).to(_lowerCAmelCase       )
         _lowerCAmelCase						=		image.cpu().permute(0  ,      2  ,      3  ,      1       )[0]
         _lowerCAmelCase						=		Image.fromarray(np.uinta(_lowerCAmelCase       )       ).convert('RGB'       ).resize((64, 64)       )
         _lowerCAmelCase						=		Image.fromarray(np.uinta(image + 4       )       ).convert('RGB'       ).resize((64, 64)       )
         _lowerCAmelCase						=		Image.fromarray(np.uinta(_lowerCAmelCase       )       ).convert('RGB'       ).resize((32, 32)       )

         if str(_lowerCAmelCase       ).startswith('mps'       ):
           _lowerCAmelCase						=		torch.manual_seed(_lowerCAmelCase       )
         else:
           _lowerCAmelCase						=		torch.Generator(device=_lowerCAmelCase       ).manual_seed(_lowerCAmelCase       )
         _lowerCAmelCase						=		{
             'example_image': example_image,
             'image': init_image,
             'mask_image': mask_image,
             'generator': generator,
             'num_inference_steps': 2,
             'guidance_scale': 6.0,
             'output_type': 'numpy',
         }
         return inputs



       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]       )					->   List[Any]:
         _lowerCAmelCase						=		self.get_dummy_components()

         # make sure here that pndm scheduler skips prk
         _lowerCAmelCase						=		PaintByExamplePipeline(**_lowerCAmelCase       )
         _lowerCAmelCase						=		pipe.to('cpu'       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         _lowerCAmelCase						=		self.get_dummy_inputs()
         _lowerCAmelCase						=		pipe(**_lowerCAmelCase       )
         _lowerCAmelCase						=		output.images

         _lowerCAmelCase						=		image[0, -3:, -3:, -1]

         assert image.shape == (1, 64, 64, 3)
         _lowerCAmelCase						=		np.array([0.4686, 0.5687, 0.4007, 0.5218, 0.5741, 0.4482, 0.4940, 0.4629, 0.4503]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2



       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   List[str]:
         _lowerCAmelCase						=		'cpu'
         _lowerCAmelCase						=		self.get_dummy_inputs()
         inputs.pop('mask_image'       )
         _lowerCAmelCase						=		self.convert_to_pt(inputs.pop('image'       )       )
         _lowerCAmelCase						=		image.clamp(0  ,      1       ) / 2

         # make sure here that pndm scheduler skips prk
         _lowerCAmelCase						=		PaintByExamplePipeline(**self.get_dummy_components()       )
         _lowerCAmelCase						=		pipe.to(_lowerCAmelCase       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         _lowerCAmelCase						=		pipe(image=_lowerCAmelCase  ,      mask_image=mask_image[:, 0]  ,      **_lowerCAmelCase       )
         _lowerCAmelCase						=		output.images

         _lowerCAmelCase						=		image.cpu().permute(0  ,      2  ,      3  ,      1       )[0]
         _lowerCAmelCase						=		mask_image.cpu().permute(0  ,      2  ,      3  ,      1       )[0]

         _lowerCAmelCase						=		Image.fromarray(np.uinta(_lowerCAmelCase       )       ).convert('RGB'       )
         _lowerCAmelCase						=		Image.fromarray(np.uinta(_lowerCAmelCase       )       ).convert('RGB'       )

         _lowerCAmelCase						=		pipe(**self.get_dummy_inputs()       )
         _lowerCAmelCase						=		output.images

         assert out_a.shape == (1, 64, 64, 3)
         assert np.abs(out_a.flatten() - out_a.flatten()       ).max() < 5e-2






       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]       )					->   Dict:
         super().test_inference_batch_single_identical(expected_max_diff=3e-3       )





@slow
@require_torch_gpu
class 						__lowercase(     unittest.TestCase   ):


       """simple docstring"""







       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Dict:
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()






       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]       )					->   Tuple:
         # make sure here that pndm scheduler skips prk
         _lowerCAmelCase						=		load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/paint_by_example/dog_in_bucket.png'       )
         _lowerCAmelCase						=		load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/paint_by_example/mask.png'       )
         _lowerCAmelCase						=		load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/paint_by_example/panda.jpg'       )

         _lowerCAmelCase						=		PaintByExamplePipeline.from_pretrained('Fantasy-Studio/Paint-by-Example'       )
         _lowerCAmelCase						=		pipe.to(_lowerCAmelCase       )
         pipe.set_progress_bar_config(disable=_lowerCAmelCase       )

         _lowerCAmelCase						=		torch.manual_seed(321       )
         _lowerCAmelCase						=		pipe(
             image=_lowerCAmelCase  ,      mask_image=_lowerCAmelCase  ,      example_image=_lowerCAmelCase  ,      generator=_lowerCAmelCase  ,      guidance_scale=5.0  ,      num_inference_steps=50  ,      output_type='np'  ,      )

         _lowerCAmelCase						=		output.images

         _lowerCAmelCase						=		image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         _lowerCAmelCase						=		np.array([0.4834, 0.4811, 0.4874, 0.5122, 0.5081, 0.5144, 0.5291, 0.5290, 0.5374]       )

         assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2


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