



import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
  import tensorflow as tf
  from tensorflow.python.framework.errors_impl import ResourceExhaustedError

  from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
  import pyanvml.pyanvml as nvml

a_			=					logging.get_logger(__name__)





def 		a__			(		_UpperCamelCase			: bool ,_UpperCamelCase			: bool							):
   def run_func(_UpperCamelCase			: List[str]							):
      @wraps(_UpperCamelCase							)
      def run_in_eager_mode(*_UpperCamelCase			: List[str] ,**_UpperCamelCase			: str							):
         return func(*_UpperCamelCase ,**_UpperCamelCase							)

      @wraps(_UpperCamelCase							)
      @tf.function(experimental_compile=_UpperCamelCase							)
      def run_in_graph_mode(*_UpperCamelCase			: Tuple ,**_UpperCamelCase			: Optional[Any]							):
         return func(*_UpperCamelCase ,**_UpperCamelCase							)

      if do_eager_mode is True:
         if use_xla is not False:
            raise ValueError(
                '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.'''							)
         return run_in_eager_mode
      else:
         return run_in_graph_mode

   return run_func





def 		a__			(		_UpperCamelCase			: int ,_UpperCamelCase			: int ,_UpperCamelCase			: int							):
   __lowerCamelCase													=    random.Random()
   __lowerCamelCase													=    [rng.randint(0 ,vocab_size - 1							) for i in range(batch_size * sequence_length							)]
   return tf.constant(_UpperCamelCase ,shape=(batch_size, sequence_length) ,dtype=tf.intaa							)





class  __lowerCAmelCase     (	lowerCAmelCase__   ):
 lowerCAmelCase__       					=  42
 lowerCAmelCase__       					=  42
 lowerCAmelCase__       					=  "TensorFlow"




 @property
 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return tf.__version__




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    # initialize GPU on separate process
    __lowerCamelCase													=    self.args.strategy
    if strategy is None:
       raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''				)
    __lowerCamelCase													=    self._prepare_inference_func(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)
    return self._measure_speed(_inference				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    __lowerCamelCase													=    self.args.strategy
    if strategy is None:
       raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''				)
    __lowerCamelCase													=    self._prepare_train_func(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)
    return self._measure_speed(_train				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    # initialize GPU on separate process
    if self.args.is_gpu:
       tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]	,				__UpperCAmelCase				)
    __lowerCamelCase													=    self.args.strategy
    if strategy is None:
       raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''				)
    __lowerCamelCase													=    self._prepare_inference_func(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)
    return self._measure_memory(_inference				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    if self.args.is_gpu:
       tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]	,				__UpperCAmelCase				)
    __lowerCamelCase													=    self.args.strategy
    if strategy is None:
       raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''				)

    __lowerCamelCase													=    self._prepare_train_func(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)
    return self._measure_memory(_train				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    __lowerCamelCase													=    self.config_dict[model_name]

    if self.args.fpaa:
       raise NotImplementedError('''Mixed precision is currently not supported.'''				)

    __lowerCamelCase													=    (
        hasattr(__UpperCAmelCase	,				'''architectures'''				)
        and isinstance(config.architectures	,				__UpperCAmelCase				)
        and len(config.architectures				) > 0
    )
    if not self.args.only_pretrain_model and has_model_class_in_config:
       try:
          __lowerCamelCase													=    '''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
          __lowerCamelCase													=    __import__('''transformers'''	,				fromlist=[model_class]				)
          __lowerCamelCase													=    getattr(__UpperCAmelCase	,				__UpperCAmelCase				)
          __lowerCamelCase													=    model_cls(__UpperCAmelCase				)
       except ImportError:
          raise ImportError(
              F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to"""
              ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''				)
    else:
       __lowerCamelCase													=    TF_MODEL_MAPPING[config.__class__](__UpperCAmelCase				)

    # encoder-decoder has vocab size saved differently
    __lowerCamelCase													=    config.vocab_size if hasattr(__UpperCAmelCase	,				'''vocab_size'''				) else config.encoder.vocab_size
    __lowerCamelCase													=    random_input_ids(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)

    @run_with_tf_optimizations(self.args.eager_mode	,				self.args.use_xla				)
    def encoder_decoder_forward():
       return model(__UpperCAmelCase	,				decoder_input_ids=__UpperCAmelCase	,				training=__UpperCAmelCase				)

    @run_with_tf_optimizations(self.args.eager_mode	,				self.args.use_xla				)
    def encoder_forward():
       return model(__UpperCAmelCase	,				training=__UpperCAmelCase				)

    __lowerCamelCase													=    encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

    return _inference




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    __lowerCamelCase													=    self.config_dict[model_name]

    if self.args.eager_mode is not False:
       raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.'''				)

    if self.args.fpaa:
       raise NotImplementedError('''Mixed precision is currently not supported.'''				)

    __lowerCamelCase													=    (
        hasattr(__UpperCAmelCase	,				'''architectures'''				)
        and isinstance(config.architectures	,				__UpperCAmelCase				)
        and len(config.architectures				) > 0
    )
    if not self.args.only_pretrain_model and has_model_class_in_config:
       try:
          __lowerCamelCase													=    '''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
          __lowerCamelCase													=    __import__('''transformers'''	,				fromlist=[model_class]				)
          __lowerCamelCase													=    getattr(__UpperCAmelCase	,				__UpperCAmelCase				)
          __lowerCamelCase													=    model_cls(__UpperCAmelCase				)
       except ImportError:
          raise ImportError(
              F"""{model_class} does not exist. If you just want to test the pretrained model, you might want to"""
              ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''				)
    else:
       __lowerCamelCase													=    TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__UpperCAmelCase				)

    # encoder-decoder has vocab size saved differently
    __lowerCamelCase													=    config.vocab_size if hasattr(__UpperCAmelCase	,				'''vocab_size'''				) else config.encoder.vocab_size
    __lowerCamelCase													=    random_input_ids(__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase				)

    @run_with_tf_optimizations(self.args.eager_mode	,				self.args.use_xla				)
    def encoder_decoder_train():
       __lowerCamelCase													=    model(__UpperCAmelCase	,				decoder_input_ids=__UpperCAmelCase	,				labels=__UpperCAmelCase	,				training=__UpperCAmelCase				)[0]
       __lowerCamelCase													=    tf.gradients(__UpperCAmelCase	,				model.trainable_variables				)
       return gradients

    @run_with_tf_optimizations(self.args.eager_mode	,				self.args.use_xla				)
    def encoder_train():
       __lowerCamelCase													=    model(__UpperCAmelCase	,				labels=__UpperCAmelCase	,				training=__UpperCAmelCase				)[0]
       __lowerCamelCase													=    tf.gradients(__UpperCAmelCase	,				model.trainable_variables				)
       return gradients

    __lowerCamelCase													=    encoder_decoder_train if config.is_encoder_decoder else encoder_train

    return _train




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    with self.args.strategy.scope():
       try:
          if self.args.is_tpu or self.args.use_xla:
             # run additional 10 times to stabilize compilation for tpu
             logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation'''				)
             timeit.repeat(__UpperCAmelCase	,				repeat=1	,				number=5				)

          # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
          __lowerCamelCase													=    timeit.repeat(
              __UpperCAmelCase	,				repeat=self.args.repeat	,				number=10	,				)

          return min(__UpperCAmelCase				) / 10.0
       except ResourceExhaustedError as e:
          self.print_fn(F"""Doesn't fit on GPU. {e}"""				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    logger.info(
        '''Note that TensorFlow allocates more memory than '''
        '''it might need to speed up computation. '''
        '''The memory reported here corresponds to the memory '''
        '''reported by `nvidia-smi`, which can vary depending '''
        '''on total available memory on the GPU that is used.'''				)
    with self.args.strategy.scope():
       try:
          if self.args.trace_memory_line_by_line:
             if not self.args.eager_mode:
                raise ValueError(
                    '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'''
                    ''' consumption line by line.'''				)
             __lowerCamelCase													=    start_memory_tracing('''transformers'''				)

          if self.args.is_tpu:
             # tpu
             raise NotImplementedError(
                 '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'''
                 ''' with `args.memory=False`'''				)
          elif self.args.is_gpu:
             # gpu
             if not is_pyanvml_available():
                logger.warning(
                    '''py3nvml not installed, we won\'t log GPU memory usage. '''
                    '''Install py3nvml (pip install py3nvml) to log information about GPU.'''				)
                __lowerCamelCase													=    '''N/A'''
             else:
                logger.info(
                    '''Measuring total GPU usage on GPU device. Make sure to not have additional processes'''
                    ''' running on the same GPU.'''				)
                # init nvml
                nvml.nvmlInit()
                func()
                __lowerCamelCase													=    nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx				)
                __lowerCamelCase													=    nvml.nvmlDeviceGetMemoryInfo(__UpperCAmelCase				)
                __lowerCamelCase													=    meminfo.used
                __lowerCamelCase													=    Memory(__UpperCAmelCase				)
                # shutdown nvml
                nvml.nvmlShutdown()
          else:
             # cpu
             if self.args.trace_memory_line_by_line:
                logger.info(
                    '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in'''
                    ''' TensorFlow.'''				)
                __lowerCamelCase													=    None
             else:
                __lowerCamelCase													=    measure_peak_memory_cpu(__UpperCAmelCase				)
                __lowerCamelCase													=    Memory(__UpperCAmelCase				) if isinstance(__UpperCAmelCase	,				__UpperCAmelCase				) else memory_bytes
          if self.args.trace_memory_line_by_line:
             __lowerCamelCase													=    stop_memory_tracing(__UpperCAmelCase				)
             if memory is None:
                __lowerCamelCase													=    summary.total
          else:
             __lowerCamelCase													=    None

          return memory, summary
       except ResourceExhaustedError as e:
          self.print_fn(F"""Doesn't fit on GPU. {e}"""				)
          return "N/A", None











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  __lowerCAmelCase     (	lowerCAmelCase__   ):




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __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(__UpperCAmelCase	,				exist_ok=__UpperCAmelCase				)
    __lowerCamelCase													=    os.path.join(__UpperCAmelCase	,				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(__UpperCAmelCase	,				range(len(__UpperCAmelCase				)				)				)				)
    __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(__UpperCAmelCase	,				exist_ok=__UpperCAmelCase				)
    __lowerCamelCase													=    os.path.join(__UpperCAmelCase	,				BART_VOCAB_FILES_NAMES['''vocab_file''']				)
    __lowerCamelCase													=    os.path.join(__UpperCAmelCase	,				BART_VOCAB_FILES_NAMES['''merges_file''']				)
    with open(self.vocab_file	,				'''w'''	,				encoding='''utf-8'''				) as fp:
       fp.write(json.dumps(__UpperCAmelCase				) + '''\n'''				)
    with open(self.merges_file	,				'''w'''	,				encoding='''utf-8'''				) as fp:
       fp.write('''\n'''.join(__UpperCAmelCase				)				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname	,				'''dpr_tokenizer'''				)				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname	,				'''dpr_tokenizer'''				)				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname	,				'''bart_tokenizer'''				)				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    shutil.rmtree(self.tmpdirname				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __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        lowerCamelCase      (						self				):



    '''simple docstring'''
    __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													=    RagRetriever(
           __UpperCAmelCase	,				question_encoder_tokenizer=self.get_dpr_tokenizer()	,				generator_tokenizer=self.get_bart_tokenizer()	,				)
    return retriever




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    __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													=    RagRetriever(
           __UpperCAmelCase	,				question_encoder_tokenizer=self.get_dpr_tokenizer()	,				generator_tokenizer=self.get_bart_tokenizer()	,				)
    else:
       __lowerCamelCase													=    RagRetriever(
           __UpperCAmelCase	,				question_encoder_tokenizer=self.get_dpr_tokenizer()	,				generator_tokenizer=self.get_bart_tokenizer()	,				index=CustomHFIndex(config.retrieval_vector_size	,				__UpperCAmelCase				)	,				)
    return retriever




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    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				)

    __lowerCamelCase													=    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'''				)				)

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

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




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_canonical_hf_index_retriever()
    __lowerCamelCase													=    np.array(
        [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=__UpperCAmelCase				)
    self.assertEqual(retrieved_doc_embeds.shape	,				(2, n_docs, self.retrieval_vector_size)				)
    self.assertEqual(len(__UpperCAmelCase				)	,				2				)
    self.assertEqual(sorted(doc_dicts[0]				)	,				['''embeddings''', '''id''', '''text''', '''title''']				)
    self.assertEqual(len(doc_dicts[0]['''id''']				)	,				__UpperCAmelCase				)
    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        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    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:
          __lowerCamelCase													=    self.get_dummy_dataset()
          retriever.save_pretrained(__UpperCAmelCase				)
          __lowerCamelCase													=    RagRetriever.from_pretrained(__UpperCAmelCase				)
          self.assertIsInstance(__UpperCAmelCase	,				__UpperCAmelCase				)
          __lowerCamelCase													=    np.array(
              [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
          __lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=1				)
          self.assertTrue(out is not None				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase				)
    __lowerCamelCase													=    np.array(
        [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=__UpperCAmelCase				)
    self.assertEqual(retrieved_doc_embeds.shape	,				(2, n_docs, self.retrieval_vector_size)				)
    self.assertEqual(len(__UpperCAmelCase				)	,				2				)
    self.assertEqual(sorted(doc_dicts[0]				)	,				['''embeddings''', '''id''', '''text''', '''title''']				)
    self.assertEqual(len(doc_dicts[0]['''id''']				)	,				__UpperCAmelCase				)
    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        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase				)
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(__UpperCAmelCase				)
       __lowerCamelCase													=    RagRetriever.from_pretrained(__UpperCAmelCase				)
       self.assertIsInstance(__UpperCAmelCase	,				__UpperCAmelCase				)
       __lowerCamelCase													=    np.array(
           [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
       __lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=1				)
       self.assertTrue(out is not None				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase				)
    __lowerCamelCase													=    np.array(
        [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=__UpperCAmelCase				)
    self.assertEqual(retrieved_doc_embeds.shape	,				(2, n_docs, self.retrieval_vector_size)				)
    self.assertEqual(len(__UpperCAmelCase				)	,				2				)
    self.assertEqual(sorted(doc_dicts[0]				)	,				['''embeddings''', '''id''', '''text''', '''title''']				)
    self.assertEqual(len(doc_dicts[0]['''id''']				)	,				__UpperCAmelCase				)
    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        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase				)
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(__UpperCAmelCase				)
       __lowerCamelCase													=    RagRetriever.from_pretrained(__UpperCAmelCase				)
       self.assertIsInstance(__UpperCAmelCase	,				__UpperCAmelCase				)
       __lowerCamelCase													=    np.array(
           [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
       __lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=1				)
       self.assertTrue(out is not None				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_legacy_index_retriever()
    __lowerCamelCase													=    np.array(
        [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=__UpperCAmelCase				)
    self.assertEqual(retrieved_doc_embeds.shape	,				(2, n_docs, self.retrieval_vector_size)				)
    self.assertEqual(len(__UpperCAmelCase				)	,				2				)
    self.assertEqual(sorted(doc_dicts[0]				)	,				['''text''', '''title''']				)
    self.assertEqual(len(doc_dicts[0]['''text''']				)	,				__UpperCAmelCase				)
    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        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.get_dummy_legacy_index_retriever()
    with tempfile.TemporaryDirectory() as tmp_dirname:
       retriever.save_pretrained(__UpperCAmelCase				)
       __lowerCamelCase													=    RagRetriever.from_pretrained(__UpperCAmelCase				)
       self.assertIsInstance(__UpperCAmelCase	,				__UpperCAmelCase				)
       __lowerCamelCase													=    np.array(
           [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
       __lowerCamelCase													=    retriever.retrieve(__UpperCAmelCase	,				n_docs=1				)
       self.assertTrue(out is not None				)




 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    import torch

    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_canonical_hf_index_retriever()
    __lowerCamelCase													=    [[5, 7], [10, 11]]
    __lowerCamelCase													=    np.array(
        [np.ones(self.retrieval_vector_size				), -np.ones(self.retrieval_vector_size				)]	,				dtype=np.floataa				)
    __lowerCamelCase													=    retriever(__UpperCAmelCase	,				__UpperCAmelCase	,				prefix=retriever.config.generator.prefix	,				n_docs=__UpperCAmelCase				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    (
        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(__UpperCAmelCase	,				__UpperCAmelCase				)
    self.assertIsInstance(__UpperCAmelCase	,				__UpperCAmelCase				)
    self.assertIsInstance(__UpperCAmelCase	,				np.ndarray				)

    __lowerCamelCase													=    retriever(
        __UpperCAmelCase	,				__UpperCAmelCase	,				prefix=retriever.config.generator.prefix	,				n_docs=__UpperCAmelCase	,				return_tensors='''pt'''	,				)
    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    (  # 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(__UpperCAmelCase	,				torch.Tensor				)
    self.assertIsInstance(__UpperCAmelCase	,				torch.Tensor				)
    self.assertIsInstance(__UpperCAmelCase	,				torch.Tensor				)




 @require_torch
 @require_tokenizers
 @require_sentencepiece
 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.get_dpr_ctx_encoder_tokenizer()
    __lowerCamelCase													=    1
    __lowerCamelCase													=    self.get_dummy_custom_hf_index_retriever(from_disk=__UpperCAmelCase				)
    retriever.set_ctx_encoder_tokenizer(__UpperCAmelCase				)

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

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






