



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_lowerCamelCase         =	{
    """configuration_marian""": ["""MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MarianConfig""", """MarianOnnxConfig"""],
}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase         =	["""MarianTokenizer"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase         =	[
          """MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """MarianForCausalLM""",
          """MarianModel""",
          """MarianMTModel""",
          """MarianPreTrainedModel""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase         =	["""TFMarianModel""", """TFMarianMTModel""", """TFMarianPreTrainedModel"""]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase         =	["""FlaxMarianModel""", """FlaxMarianMTModel""", """FlaxMarianPreTrainedModel"""]

if TYPE_CHECKING:
      from .configuration_marian import MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP, MarianConfig, MarianOnnxConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_marian import MarianTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_marian import (
                MARIAN_PRETRAINED_MODEL_ARCHIVE_LIST,
                MarianForCausalLM,
                MarianModel,
                MarianMTModel,
                MarianPreTrainedModel,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, FlaxMarianPreTrainedModel

else:
      import sys

      _lowerCamelCase         =	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)











import logging
import random

import ray

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


__UpperCAmelCase    	=  logging.getLogger(__name__)


class 						lowerCamelCase__			:


						def __init__(			self    :	Optional[Any]      ):
													a__:							Tuple									=False


						def 	_lowerCamelCase      (			self    :	Dict   ,							_a    :	Any   ,							_a    :	Union[str, Any]   ,							_a    :	List[str]   ,							_a    :	Optional[int]      ):
													if not self.initialized:
																				a__:							Any									=RagRetriever(
																				    _a   ,							question_encoder_tokenizer=_a   ,							generator_tokenizer=_a   ,							index=_a   ,							init_retrieval=_a   ,							)
																				a__:							str									=True


						def 	_lowerCamelCase      (			self    :	List[str]      ):
													self.retriever.index.init_index()


						def 	_lowerCamelCase      (			self    :	Optional[int]      ):
													# delete the old self.retriever object before assigning the new index
													del self.retriever
													a__:							Dict									=False







						def 	_lowerCamelCase      (			self    :	str   ,							_a    :	List[Any]   ,							_a    :	Any      ):
													a__				,      a__:							List[str]									=self.retriever._main_retrieve(_a   ,							_a      )
													a__:							List[str]									=self.retriever.index.get_doc_dicts(_a      )
													return doc_ids, retrieved_doc_embeds, doc_dicts


class 						lowerCamelCase__			(		_a ):


						def __init__(			self    :	Optional[int]   ,							_a    :	List[Any]   ,							_a    :	Any   ,							_a    :	Optional[Any]   ,							_a    :	Union[str, Any]   ,							_a    :	str=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   ,							)

													a__:							Optional[Any]									=retrieval_workers
													a__:							str									=question_encoder_tokenizer
													a__:							Optional[int]									=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    :	List[Any]      ):
													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    :	List[Any]   ,							_a    :	Union[str, Any]   ,							_a    :	Union[str, Any]      ):
													if len(self.retrieval_workers      ) > 0:
																				# Select a random retrieval actor.
																				a__:							Tuple									=self.retrieval_workers[random.randint(0   ,							len(self.retrieval_workers      ) - 1      )]
																				a__				,      a__				,      a__:							Union[str, Any]									=ray.get(
																				    random_worker.retrieve.remote(_a   ,							_a      )      )
													else:
																				a__				,      a__:							List[Any]									=self._main_retrieve(_a   ,							_a      )
																				a__:							List[str]									=self.index.get_doc_dicts(_a      )
													return retrieved_doc_embeds, doc_ids, doc_dicts


						@classmethod
						def 	_lowerCamelCase      (			cls    :	str   ,							_a    :	Union[str, Any]   ,							_a    :	Any=None   ,							**_a    :	Dict      ):
													return super(_a   ,							cls      ).get_tokenizers(_a   ,							_a   ,							**_a      )


						@classmethod
						def 	_lowerCamelCase      (			cls    :	Dict   ,							_a    :	Optional[int]   ,							_a    :	Tuple   ,							_a    :	int=None   ,							**_a    :	List[str]      ):
													a__:							Union[str, Any]									=kwargs.pop("config"   ,							_a      ) or RagConfig.from_pretrained(_a   ,							**_a      )
													a__:							List[Any]									=RagTokenizer.from_pretrained(_a   ,							config=_a      )
													a__:							str									=rag_tokenizer.question_encoder
													a__:							Any									=rag_tokenizer.generator

													if indexed_dataset is not None:
																				a__:							Dict									="custom"
																				a__:							Dict									=CustomHFIndex(config.retrieval_vector_size   ,							_a      )
													else:
																				a__:							List[str]									=cls._build_index(_a      )

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







						def 	_lowerCamelCase      (			self    :	Union[str, Any]      ):
													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
													a__:							str									=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
													    ]      )





