




'''simple docstring'''




import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
			import transformer_engine.pytorch as te




def 						snake_case__    ( lowerCamelCase__				:   Union[str, Any]			,		lowerCamelCase__				:   int=True			,		lowerCamelCase__				:   int=True			,		lowerCamelCase__				:   Tuple=True			)   ->   str:
					if not is_fpa_available():
										raise ImportError('''Using `convert_model` requires transformer_engine to be installed.'''			)
					for name, module in model.named_children():
										if isinstance(lowerCamelCase__			,		nn.Linear			) and to_transformer_engine and _convert_linear:
															# Return early if the linear layer weights are not multiples of 16
															if any(p % 1_6 != 0 for p in module.weight.shape			):
																				return
															A_ :     Optional[Any] =							module.bias is not None
															A_ :     str =							te.Linear(
															    module.in_features			,		module.out_features			,		bias=lowerCamelCase__			,		params_dtype=module.weight.dtype			)
															A_ :     Union[str, Any] =							module.weight.data.clone()
															if has_bias:
																				A_ :     Optional[int] =							module.bias.data.clone()

															setattr(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
										elif isinstance(lowerCamelCase__			,		nn.LayerNorm			) and to_transformer_engine and _convert_ln:
															A_ :     Union[str, Any] =							te.LayerNorm(module.normalized_shape[0]			,		eps=module.eps			,		params_dtype=module.weight.dtype			)
															A_ :     List[str] =							module.weight.data.clone()
															A_ :     str =							module.bias.data.clone()

															setattr(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
										elif isinstance(lowerCamelCase__			,		te.Linear			) and not to_transformer_engine and _convert_linear:
															A_ :     Any =							module.bias is not None
															A_ :     int =							nn.Linear(
															    module.in_features			,		module.out_features			,		bias=lowerCamelCase__			,		params_dtype=module.weight.dtype			)
															A_ :     List[Any] =							module.weight.data.clone()
															if has_bias:
																				A_ :     Dict =							module.bias.data.clone()

															setattr(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
										elif isinstance(lowerCamelCase__			,		te.LayerNorm			) and not to_transformer_engine and _convert_ln:
															A_ :     Any =							nn.LayerNorm(module.normalized_shape[0]			,		eps=module.eps			,		params_dtype=module.weight.dtype			)
															A_ :     int =							module.weight.data.clone()
															A_ :     Optional[Any] =							module.bias.data.clone()

															setattr(lowerCamelCase__			,		lowerCamelCase__			,		lowerCamelCase__			)
										else:
															convert_model(
															    lowerCamelCase__			,		to_transformer_engine=lowerCamelCase__			,		_convert_linear=_convert_linear			,		_convert_ln=_convert_ln			,		)





def 						snake_case__    ( lowerCamelCase__				:   str			)   ->   Dict:
					if not is_fpa_available():
										raise ImportError('''Using `has_transformer_engine_layers` requires transformer_engine to be installed.'''			)
					for m in model.modules():
										if isinstance(lowerCamelCase__			,		(te.LayerNorm, te.Linear)			):
															return True
					return False









'''simple docstring'''




import logging
import random

import ray

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


snake_case__          =						logging.getLogger(__name__)






class     UpperCamelCase_     :







						"""simple docstring"""


						def __init__(     self      :       Tuple    ):





											"""simple docstring"""







											A_ :     Optional[int] =							False







						def       _a    (     self      :       Any							, _lowerCamelCase      :       List[str]							, _lowerCamelCase      :       Any							, _lowerCamelCase      :       str							, _lowerCamelCase      :       int    ):





											"""simple docstring"""







											if not self.initialized:
																A_ :     Optional[Any] =							RagRetriever(
																    _lowerCamelCase							, question_encoder_tokenizer=_lowerCamelCase							, generator_tokenizer=_lowerCamelCase							, index=_lowerCamelCase							, init_retrieval=_lowerCamelCase							, )
																A_ :     Optional[Any] =							True







						def       _a    (     self      :       int    ):





											"""simple docstring"""







											self.retriever.index.init_index()







						def       _a    (     self      :       Any    ):





											"""simple docstring"""







											del self.retriever
											A_ :     List[Any] =							False







						def       _a    (     self      :       Optional[int]							, _lowerCamelCase      :       Union[str, Any]							, _lowerCamelCase      :       Union[str, Any]    ):





											"""simple docstring"""







											A_ ,A_ :     Dict =							self.retriever._main_retrieve(_lowerCamelCase							, _lowerCamelCase    )
											A_ :     int =							self.retriever.index.get_doc_dicts(_lowerCamelCase    )
											return doc_ids, retrieved_doc_embeds, doc_dicts






class     UpperCamelCase_     (a__     ):







						"""simple docstring"""


						def __init__(     self      :       int							, _lowerCamelCase      :       Optional[Any]							, _lowerCamelCase      :       Dict							, _lowerCamelCase      :       Optional[int]							, _lowerCamelCase      :       Dict							, _lowerCamelCase      :       Tuple=None    ):





											"""simple docstring"""







											if index is not None and index.is_initialized() and len(_lowerCamelCase    ) > 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__(
											    _lowerCamelCase							, question_encoder_tokenizer=_lowerCamelCase							, generator_tokenizer=_lowerCamelCase							, index=_lowerCamelCase							, init_retrieval=_lowerCamelCase							, )

											A_ :     Tuple =							retrieval_workers
											A_ :     Any =							question_encoder_tokenizer
											A_ :     Dict =							generator_tokenizer
											if len(self.retrieval_workers    ) > 0:
																ray.get(
																    [
																        worker.create_rag_retriever.remote(_lowerCamelCase							, _lowerCamelCase							, _lowerCamelCase							, _lowerCamelCase    )
																        for worker in self.retrieval_workers
																    ]    )







						def       _a    (     self      :       Dict    ):





											"""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       _a    (     self      :       Dict							, _lowerCamelCase      :       Tuple							, _lowerCamelCase      :       int    ):





											"""simple docstring"""







											if len(self.retrieval_workers    ) > 0:
																# Select a random retrieval actor.
																A_ :     Optional[int] =							self.retrieval_workers[random.randint(0							, len(self.retrieval_workers    ) - 1    )]
																A_ ,A_ ,A_ :     Union[str, Any] =							ray.get(
																    random_worker.retrieve.remote(_lowerCamelCase							, _lowerCamelCase    )    )
											else:
																A_ ,A_ :     List[str] =							self._main_retrieve(_lowerCamelCase							, _lowerCamelCase    )
																A_ :     Union[str, Any] =							self.index.get_doc_dicts(_lowerCamelCase    )
											return retrieved_doc_embeds, doc_ids, doc_dicts







						@classmethod
						def       _a    (     cls      :       List[str]							, _lowerCamelCase      :       Union[str, Any]							, _lowerCamelCase      :       Optional[Any]=None							, **_lowerCamelCase      :       str    ):





											"""simple docstring"""







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







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





											"""simple docstring"""







											A_ :     Tuple =							kwargs.pop('''config'''							, _lowerCamelCase    ) or RagConfig.from_pretrained(_lowerCamelCase							, **_lowerCamelCase    )
											A_ :     List[Any] =							RagTokenizer.from_pretrained(_lowerCamelCase							, config=_lowerCamelCase    )
											A_ :     Union[str, Any] =							rag_tokenizer.question_encoder
											A_ :     Dict =							rag_tokenizer.generator

											if indexed_dataset is not None:
																A_ :     Any =							'''custom'''
																A_ :     int =							CustomHFIndex(config.retrieval_vector_size							, _lowerCamelCase    )
											else:
																A_ :     Optional[int] =							cls._build_index(_lowerCamelCase    )

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







						def       _a    (     self      :       Optional[Any]    ):





											"""simple docstring"""







											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_ :     Dict =							self._build_index(self.config    )

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



