

import logging
import random

import ray

from transformers import RagConfig, RagRetriever, RagTokenizer
from transformers.models.rag.retrieval_rag import CustomHFIndex


UpperCamelCase__	:   Union[str, Any]								=     logging.getLogger(__name__)



class    __snake_case	:

  def __init__(       self):
      SCREAMING_SNAKE_CASE_						=    False

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A    ,		_A):
      if not self.initialized:
          SCREAMING_SNAKE_CASE_						=    RagRetriever(
              _A    ,		question_encoder_tokenizer=_A    ,		generator_tokenizer=_A    ,		index=_A    ,		init_retrieval=_A    ,		)
          SCREAMING_SNAKE_CASE_						=    True

  def     lowerCAmelCase__  (       self):
      self.retriever.index.init_index()

  def     lowerCAmelCase__  (       self):
      # delete the old self.retriever object before assigning the new index
      del self.retriever
      SCREAMING_SNAKE_CASE_						=    False


  def     lowerCAmelCase__  (       self    ,		_A    ,		_A):
      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self.retriever._main_retrieve(_A    ,		_A)
      SCREAMING_SNAKE_CASE_						=    self.retriever.index.get_doc_dicts(_A)
      return doc_ids, retrieved_doc_embeds, doc_dicts






class    __snake_case	(     lowerCAmelCase__							):

  def __init__(       self    ,		_A    ,		_A    ,		_A    ,		_A    ,		_A=None):
      if index is not None and index.is_initialized() and len(_A) > 0:
          raise ValueError(
              'When using Ray for distributed fine-tuning, '
              'you\'ll need to provide the paths instead, '
              'as the dataset and the index are loaded '
              'separately. More info in examples/rag/use_own_knowledge_dataset.py ')

      super().__init__(
          _A    ,		question_encoder_tokenizer=_A    ,		generator_tokenizer=_A    ,		index=_A    ,		init_retrieval=_A    ,		)

      SCREAMING_SNAKE_CASE_						=    retrieval_workers
      SCREAMING_SNAKE_CASE_						=    question_encoder_tokenizer
      SCREAMING_SNAKE_CASE_						=    generator_tokenizer
      if len(self.retrieval_workers) > 0:
          ray.get(
              [
                  worker.create_rag_retriever.remote(_A    ,		_A    ,		_A    ,		_A)
                  for worker in self.retrieval_workers
              ])

  def     lowerCAmelCase__  (       self):
      logger.info('initializing retrieval')

      if len(self.retrieval_workers) > 0:
          ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers])
      else:
          # Non-distributed training. Load index into this same process.
          self.index.init_index()

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A):
      if len(self.retrieval_workers) > 0:
          # Select a random retrieval actor.
          SCREAMING_SNAKE_CASE_						=    self.retrieval_workers[random.randint(0    ,		len(self.retrieval_workers) - 1)]
          SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    ray.get(
              random_worker.retrieve.remote(_A    ,		_A))
      else:
          SCREAMING_SNAKE_CASE_				,      SCREAMING_SNAKE_CASE_						=    self._main_retrieve(_A    ,		_A)
          SCREAMING_SNAKE_CASE_						=    self.index.get_doc_dicts(_A)
      return retrieved_doc_embeds, doc_ids, doc_dicts

  @classmethod
  def     lowerCAmelCase__  (       cls    ,		_A    ,		_A=None    ,		**_A):
      return super(_A    ,		cls).get_tokenizers(_A    ,		_A    ,		**_A)

  @classmethod
  def     lowerCAmelCase__  (       cls    ,		_A    ,		_A    ,		_A=None    ,		**_A):
      SCREAMING_SNAKE_CASE_						=    kwargs.pop('config'    ,		_A) or RagConfig.from_pretrained(_A    ,		**_A)
      SCREAMING_SNAKE_CASE_						=    RagTokenizer.from_pretrained(_A    ,		config=_A)
      SCREAMING_SNAKE_CASE_						=    rag_tokenizer.question_encoder
      SCREAMING_SNAKE_CASE_						=    rag_tokenizer.generator

      if indexed_dataset is not None:
          SCREAMING_SNAKE_CASE_						=    'custom'
          SCREAMING_SNAKE_CASE_						=    CustomHFIndex(config.retrieval_vector_size    ,		_A)
      else:
          SCREAMING_SNAKE_CASE_						=    cls._build_index(_A)

      return cls(
          _A    ,		question_encoder_tokenizer=_A    ,		generator_tokenizer=_A    ,		retrieval_workers=_A    ,		index=_A    ,		)


  def     lowerCAmelCase__  (       self):
      logger.info('re-loading the new dataset with embeddings')
      # access from the training loop

      ray.get([worker.clear_object.remote() for worker in self.retrieval_workers])

      # build the index object again
      SCREAMING_SNAKE_CASE_						=    self._build_index(self.config)

      ray.get(
          [
              worker.create_rag_retriever.remote(
                  self.config    ,		self.question_encoder_tokenizer    ,		self.generator_tokenizer    ,		_A)
              for worker in self.retrieval_workers
          ])





import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


UpperCamelCase__	:   List[str]								=     get_tests_dir("fixtures/spiece.model")



@require_sentencepiece
@require_tokenizers
class    __snake_case	(     lowerCAmelCase__  ,			unittest.TestCase							):
  __lowerCAmelCase  :						Union[str, Any]    			=	ErnieMTokenizer
  __lowerCAmelCase  :						Union[str, Any]    			=	False
  __lowerCAmelCase  :						Optional[int]    			=	True
  __lowerCAmelCase  :						List[str]    			=	False
  __lowerCAmelCase  :						List[str]    			=	False

  def     lowerCAmelCase__  (       self):
      super().setUp()

      # We have a SentencePiece fixture for testing
      SCREAMING_SNAKE_CASE_						=    ErnieMTokenizer(_A    ,		unk_token='<unk>'    ,		pad_token='<pad>')
      tokenizer.save_pretrained(self.tmpdirname)

  def     lowerCAmelCase__  (       self    ,		_A):
      SCREAMING_SNAKE_CASE_						=    'this is a test'
      SCREAMING_SNAKE_CASE_						=    'this is a test'
      return input_text, output_text

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    '<pad>'
      SCREAMING_SNAKE_CASE_						=    0

      self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A)    ,		_A)
      self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A)    ,		_A)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    list(self.get_tokenizer().get_vocab().keys())

      self.assertEqual(vocab_keys[0]    ,		'<pad>')
      self.assertEqual(vocab_keys[1]    ,		'<unk>')
      self.assertEqual(vocab_keys[-1]    ,		'▁eloquent')
      self.assertEqual(len(_A)    ,		30000)

  def     lowerCAmelCase__  (       self):
      self.assertEqual(self.get_tokenizer().vocab_size    ,		30000)

  def     lowerCAmelCase__  (       self):
      if not self.test_rust_tokenizer:
          return

      SCREAMING_SNAKE_CASE_						=    self.get_tokenizer()
      SCREAMING_SNAKE_CASE_						=    self.get_rust_tokenizer()

      SCREAMING_SNAKE_CASE_						=    'I was born in 92000, and this is falsé.'

      SCREAMING_SNAKE_CASE_						=    tokenizer.tokenize(_A)
      SCREAMING_SNAKE_CASE_						=    rust_tokenizer.tokenize(_A)
      self.assertListEqual(_A    ,		_A)

      SCREAMING_SNAKE_CASE_						=    tokenizer.encode(_A    ,		add_special_tokens=_A)
      SCREAMING_SNAKE_CASE_						=    rust_tokenizer.encode(_A    ,		add_special_tokens=_A)
      self.assertListEqual(_A    ,		_A)

      SCREAMING_SNAKE_CASE_						=    self.get_rust_tokenizer()
      SCREAMING_SNAKE_CASE_						=    tokenizer.encode(_A)
      SCREAMING_SNAKE_CASE_						=    rust_tokenizer.encode(_A)
      self.assertListEqual(_A    ,		_A)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    ErnieMTokenizer(_A    ,		do_lower_case=_A    ,		unk_token='<unk>'    ,		pad_token='<pad>')

      SCREAMING_SNAKE_CASE_						=    tokenizer.tokenize('This is a test')
      self.assertListEqual(_A    ,		['▁this', '▁is', '▁a', '▁test'])

      self.assertListEqual(tokenizer.convert_tokens_to_ids(_A)    ,		[48, 25, 21, 1289])

      SCREAMING_SNAKE_CASE_						=    tokenizer.tokenize('I was born in 92000, and this is falsé.')
      # ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
      self.assertListEqual(
          _A    ,		['▁i', '▁was', '▁born', '▁in', '9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'])
      SCREAMING_SNAKE_CASE_						=    tokenizer.convert_tokens_to_ids(_A)
      self.assertListEqual(_A    ,		[31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9])

      SCREAMING_SNAKE_CASE_						=    tokenizer.convert_ids_to_tokens(_A)
      self.assertListEqual(
          _A    ,		['▁i', '▁was', '▁born', '▁in', '9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.']    ,		)

  def     lowerCAmelCase__  (       self):
      SCREAMING_SNAKE_CASE_						=    ErnieMTokenizer(_A    ,		unk_token='<unk>'    ,		pad_token='<pad>')

      SCREAMING_SNAKE_CASE_						=    tokenizer.encode('sequence builders')
      SCREAMING_SNAKE_CASE_						=    tokenizer.encode('multi-sequence build')

      SCREAMING_SNAKE_CASE_						=    tokenizer.build_inputs_with_special_tokens(_A)
      SCREAMING_SNAKE_CASE_						=    tokenizer.build_inputs_with_special_tokens(_A    ,		_A)

      assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
      assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
          tokenizer.sep_token_id
      ] + text_a + [tokenizer.sep_token_id]


  @slow
  def     lowerCAmelCase__  (       self):
      # fmt: off
      SCREAMING_SNAKE_CASE_						=    {'input_ids': [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 9, 304, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 5, 5, 5, 16, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 122009, 115774, 23, 3559, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
      # fmt: on

      self.tokenizer_integration_test_util(
          expected_encoding=_A    ,		model_name='susnato/ernie-m-base_pytorch'    ,		sequences=[
              'Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides '
              'general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural '
              'Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained '
              'models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.',
              'BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly '
              'conditioning on both left and right context in all layers.',
              'The quick brown fox jumps over the lazy dog.',
          ]    ,		)


