



import logging
import random

import ray

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


__snake_case						:List[Any]      		=     logging.getLogger(__name__)

class     _A       :



       def __init__(		self							:     List[str]):


           '''simple docstring'''

           __a						       =				False



       def 		_lowerCamelCase			(		self							:     Any     ,		__SCREAMING_SNAKE_CASE							:     Optional[Any]     ,		__SCREAMING_SNAKE_CASE							:     Optional[Any]     ,		__SCREAMING_SNAKE_CASE							:     List[str]     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]):


           '''simple docstring'''

           if not self.initialized:
               __a						       =				RagRetriever(
                   __SCREAMING_SNAKE_CASE     ,		question_encoder_tokenizer=__SCREAMING_SNAKE_CASE     ,		generator_tokenizer=__SCREAMING_SNAKE_CASE     ,		index=__SCREAMING_SNAKE_CASE     ,		init_retrieval=__SCREAMING_SNAKE_CASE     ,		)
               __a						       =				True



       def 		_lowerCamelCase			(		self							:     List[str]):


           '''simple docstring'''

           self.retriever.index.init_index()





       def 		_lowerCamelCase			(		self							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]):


           '''simple docstring'''

           __a       ,   __a						       =				self.retriever._main_retrieve(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
           return doc_ids, retrieved_doc_embeds


class     _A       (	__UpperCAmelCase    ):



       def __init__(		self							:     Optional[Any]     ,		__SCREAMING_SNAKE_CASE							:     List[Any]     ,		__SCREAMING_SNAKE_CASE							:     List[str]     ,		__SCREAMING_SNAKE_CASE							:     List[str]     ,		__SCREAMING_SNAKE_CASE							:     int     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]=None):


           '''simple docstring'''

           if index is not None and index.is_initialized() and len(__SCREAMING_SNAKE_CASE) > 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__(
               __SCREAMING_SNAKE_CASE     ,		question_encoder_tokenizer=__SCREAMING_SNAKE_CASE     ,		generator_tokenizer=__SCREAMING_SNAKE_CASE     ,		index=__SCREAMING_SNAKE_CASE     ,		init_retrieval=__SCREAMING_SNAKE_CASE     ,		)
           __a						       =				retrieval_workers
           if len(self.retrieval_workers) > 0:
               ray.get(
                   [
                       worker.create_rag_retriever.remote(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
                       for worker in self.retrieval_workers
                   ])



       def 		_lowerCamelCase			(		self							:     List[Any]):


           '''simple docstring'''

           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							:     Dict     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]     ,		__SCREAMING_SNAKE_CASE							:     List[Any]):


           '''simple docstring'''

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



       @classmethod
       def 		_lowerCamelCase			(		cls							:     Any     ,		__SCREAMING_SNAKE_CASE							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Tuple=None     ,		**__SCREAMING_SNAKE_CASE							:     Optional[int]):


           '''simple docstring'''

           return super(__SCREAMING_SNAKE_CASE     ,		cls).get_tokenizers(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)





       @classmethod
       def 		_lowerCamelCase			(		cls							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Optional[int]     ,		__SCREAMING_SNAKE_CASE							:     str     ,		__SCREAMING_SNAKE_CASE							:     str=None     ,		**__SCREAMING_SNAKE_CASE							:     List[Any]):


           '''simple docstring'''

           __a						       =				kwargs.pop('''config'''     ,		__SCREAMING_SNAKE_CASE) or RagConfig.from_pretrained(__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)
           __a						       =				RagTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE     ,		config=__SCREAMING_SNAKE_CASE)
           __a						       =				rag_tokenizer.question_encoder
           __a						       =				rag_tokenizer.generator
           if indexed_dataset is not None:
               __a						       =				'''custom'''
               __a						       =				CustomHFIndex(config.retrieval_vector_size     ,		__SCREAMING_SNAKE_CASE)
           else:
               __a						       =				cls._build_index(__SCREAMING_SNAKE_CASE)
           return cls(
               __SCREAMING_SNAKE_CASE     ,		question_encoder_tokenizer=__SCREAMING_SNAKE_CASE     ,		generator_tokenizer=__SCREAMING_SNAKE_CASE     ,		retrieval_workers=__SCREAMING_SNAKE_CASE     ,		index=__SCREAMING_SNAKE_CASE     ,		)










import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm
 import torch_xla.debug.metrics as met

class     _A       (	__UpperCAmelCase    ):



       def __init__(		self							:     List[Any]     ,		*__SCREAMING_SNAKE_CASE							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Any=None     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]=None     ,		**__SCREAMING_SNAKE_CASE							:     str):


           '''simple docstring'''

           super().__init__(*__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)
           __a						       =				eval_examples
           __a						       =				post_process_function



       def 		_lowerCamelCase			(		self							:     Dict     ,		__SCREAMING_SNAKE_CASE							:     Optional[Dataset] = None     ,		__SCREAMING_SNAKE_CASE							:     List[Any]=None     ,		__SCREAMING_SNAKE_CASE							:     Optional[List[str]] = None     ,		__SCREAMING_SNAKE_CASE							:     str = "eval"     ,		**__SCREAMING_SNAKE_CASE							:     Any     ,		):


           '''simple docstring'''

           __a						       =				gen_kwargs.copy()
           __a						       =				(
               gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''') is not None else self.args.generation_max_length
           )
           __a						       =				(
               gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''') is not None else self.args.generation_num_beams
           )
           __a						       =				gen_kwargs

           __a						       =				self.eval_dataset if eval_dataset is None else eval_dataset
           __a						       =				self.get_eval_dataloader(__SCREAMING_SNAKE_CASE)
           __a						       =				self.eval_examples if eval_examples is None else eval_examples

           # Temporarily disable metric computation, we will do it in the loop here.
           __a						       =				self.compute_metrics
           __a						       =				None
           __a						       =				time.time()
           __a						       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           try:
               __a						       =				eval_loop(
                   __SCREAMING_SNAKE_CASE     ,		description='''Evaluation'''     ,		prediction_loss_only=True if compute_metrics is None else None     ,		ignore_keys=__SCREAMING_SNAKE_CASE     ,		metric_key_prefix=__SCREAMING_SNAKE_CASE     ,		)
           finally:
               __a						       =				compute_metrics
           __a						       =				self.args.eval_batch_size * self.args.world_size
           if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
               start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
           output.metrics.update(
               speed_metrics(
                   __SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		num_samples=output.num_samples     ,		num_steps=math.ceil(output.num_samples / total_batch_size)     ,		))

           if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
               # Only the main node write the results by default
               __a						       =				self.post_process_function(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
               __a						       =				self.compute_metrics(__SCREAMING_SNAKE_CASE)

               # Prefix all keys with metric_key_prefix + '_'
               for key in list(metrics.keys()):
                   if not key.startswith(F'{metric_key_prefix}_'):
                       __a						       =				metrics.pop(__SCREAMING_SNAKE_CASE)

               metrics.update(output.metrics)
           else:
               __a						       =				output.metrics

           if self.args.should_log:
               # Only the main node log the results by default
               self.log(__SCREAMING_SNAKE_CASE)

           if self.args.tpu_metrics_debug or self.args.debug:
               # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
               xm.master_print(met.metrics_report())

           __a						       =				self.callback_handler.on_evaluate(self.args     ,		self.state     ,		self.control     ,		__SCREAMING_SNAKE_CASE)
           return metrics





       def 		_lowerCamelCase			(		self							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Any     ,		__SCREAMING_SNAKE_CASE							:     int     ,		__SCREAMING_SNAKE_CASE							:     Tuple=None     ,		__SCREAMING_SNAKE_CASE							:     str = "test"     ,		**__SCREAMING_SNAKE_CASE							:     Dict):


           '''simple docstring'''

           __a						       =				gen_kwargs.copy()

           __a						       =				self.get_test_dataloader(__SCREAMING_SNAKE_CASE)

           # Temporarily disable metric computation, we will do it in the loop here.
           __a						       =				self.compute_metrics
           __a						       =				None
           __a						       =				time.time()
           __a						       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           try:
               __a						       =				eval_loop(
                   __SCREAMING_SNAKE_CASE     ,		description='''Prediction'''     ,		prediction_loss_only=True if compute_metrics is None else None     ,		ignore_keys=__SCREAMING_SNAKE_CASE     ,		metric_key_prefix=__SCREAMING_SNAKE_CASE     ,		)
           finally:
               __a						       =				compute_metrics

           __a						       =				self.args.eval_batch_size * self.args.world_size
           if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
               start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
           output.metrics.update(
               speed_metrics(
                   __SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		num_samples=output.num_samples     ,		num_steps=math.ceil(output.num_samples / total_batch_size)     ,		))
           if self.post_process_function is None or self.compute_metrics is None:
               return output

           __a						       =				self.post_process_function(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		'''predict''')
           __a						       =				self.compute_metrics(__SCREAMING_SNAKE_CASE)

           # Prefix all keys with metric_key_prefix + '_'
           for key in list(metrics.keys()):
               if not key.startswith(F'{metric_key_prefix}_'):
                   __a						       =				metrics.pop(__SCREAMING_SNAKE_CASE)
           metrics.update(output.metrics)
           return PredictionOutput(predictions=predictions.predictions     ,		label_ids=predictions.label_ids     ,		metrics=__SCREAMING_SNAKE_CASE)





