




'''simple docstring'''




import inspect
import warnings

import torch

from .state import AcceleratorState, GradientState
from .utils import DistributedType, honor_type, is_tpu_available


if is_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm

def    _UpperCamelCase      (				SCREAMING_SNAKE_CASE__			:      Tuple       ,						SCREAMING_SNAKE_CASE__			:      Dict       ):
 '''simple docstring'''





 if isinstance(SCREAMING_SNAKE_CASE__       ,						(list, tuple)       ):
  return honor_type(SCREAMING_SNAKE_CASE__       ,						(move_to_device(SCREAMING_SNAKE_CASE__       ,						SCREAMING_SNAKE_CASE__       ) for t in state)       )
 elif isinstance(SCREAMING_SNAKE_CASE__       ,						SCREAMING_SNAKE_CASE__       ):
  return type(SCREAMING_SNAKE_CASE__       )({k: move_to_device(SCREAMING_SNAKE_CASE__       ,						SCREAMING_SNAKE_CASE__       ) for k, v in state.items()}       )
 elif isinstance(SCREAMING_SNAKE_CASE__       ,						torch.Tensor       ):
  return state.to(SCREAMING_SNAKE_CASE__       )
 return state







class 						lowerCAmelCase_   ( torch.optim.Optimizer   ):







  '''simple docstring'''







  def __init__(						self    :	List[str]						,		_UpperCAmelCase    :	Any						,		_UpperCAmelCase    :	Union[str, Any]=True						,		_UpperCAmelCase    :	List[str]=None ):






   """simple docstring"""






   UpperCAmelCase__										=    optimizer
   UpperCAmelCase__										=    scaler
   UpperCAmelCase__										=    AcceleratorState()
   UpperCAmelCase__										=    GradientState()
   UpperCAmelCase__										=    device_placement
   UpperCAmelCase__										=    False
   UpperCAmelCase__										=    None

   # Handle device placement
   if device_placement:
    UpperCAmelCase__										=    self.optimizer.state_dict()
    if self.accelerator_state.distributed_type == DistributedType.TPU:
     xm.send_cpu_data_to_device(_UpperCAmelCase						,		self.accelerator_state.device )
    else:
     UpperCAmelCase__										=    move_to_device(_UpperCAmelCase						,		self.accelerator_state.device )
    self.optimizer.load_state_dict(_UpperCAmelCase )


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Dict ):






   """simple docstring"""






   return self.optimizer.state


  @state.setter
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int]						,		_UpperCAmelCase    :	List[str] ):






   """simple docstring"""






   UpperCAmelCase__										=    state


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any ):






   """simple docstring"""






   return self.optimizer.param_groups


  @param_groups.setter
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int]						,		_UpperCAmelCase    :	List[Any] ):






   """simple docstring"""






   UpperCAmelCase__										=    param_groups


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[Any] ):






   """simple docstring"""






   return self.optimizer.defaults


  @defaults.setter
  def 							SCREAMING_SNAKE_CASE__			(						self    :	int						,		_UpperCAmelCase    :	str ):






   """simple docstring"""






   UpperCAmelCase__										=    defaults


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int]						,		_UpperCAmelCase    :	Union[str, Any] ):






   """simple docstring"""






   self.optimizer.add_param_group(_UpperCAmelCase )


  def 							SCREAMING_SNAKE_CASE__			(						self    :	List[str]						,		_UpperCAmelCase    :	Tuple ):






   """simple docstring"""






   if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
    xm.send_cpu_data_to_device(_UpperCAmelCase						,		self.accelerator_state.device )
   self.optimizer.load_state_dict(_UpperCAmelCase )


  def 							SCREAMING_SNAKE_CASE__			(						self    :	str ):






   """simple docstring"""






   return self.optimizer.state_dict()


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int]						,		_UpperCAmelCase    :	List[Any]=None ):






   """simple docstring"""






   if self.gradient_state.sync_gradients:
    UpperCAmelCase__										=    """set_to_none""" in inspect.signature(self.optimizer.zero_grad ).parameters
    if accept_arg:
     if set_to_none is None:
      UpperCAmelCase__										=    False
     self.optimizer.zero_grad(set_to_none=_UpperCAmelCase )
    else:
     if set_to_none is not None:
      raise ValueError("""`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.""" )
     self.optimizer.zero_grad()


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any						,		_UpperCAmelCase    :	List[str]=None ):






   """simple docstring"""






   if self.gradient_state.sync_gradients:
    if self.accelerator_state.distributed_type == DistributedType.TPU:
     UpperCAmelCase__										=    {"""closure""": closure} if closure is not None else {}
     xm.optimizer_step(self.optimizer						,		optimizer_args=_UpperCAmelCase )
    elif self.scaler is not None:
     UpperCAmelCase__										=    False
     if self._last_scale is None:
      # `get_scale` is an async operation requiring full synchronization
      # on CPU and GPUs before finishing. As a result, we store away
      # the prior one to reduce the call overhead
      UpperCAmelCase__										=    self.scaler.get_scale()
      UpperCAmelCase__										=    True
     self.scaler.step(self.optimizer						,		_UpperCAmelCase )
     self.scaler.update()
     UpperCAmelCase__										=    self.scaler.get_scale()
     if not new_scale:
      # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
      UpperCAmelCase__										=    scale_after < self._last_scale
     UpperCAmelCase__										=    scale_after

    else:
     self.optimizer.step(_UpperCAmelCase )


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[Any]						,		_UpperCAmelCase    :	str ):






   """simple docstring"""






   for param_group in self.optimizer.param_groups:
    UpperCAmelCase__										=    [parameters_map.get(_UpperCAmelCase						,		_UpperCAmelCase ) for p in param_group["""params"""]]


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	str ):






   """simple docstring"""






   warnings.warn(
       """The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use """
       """`optimizer.step_was_skipped` instead."""						,		_UpperCAmelCase						,		)
   return self._is_overflow


  @property
  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int] ):






   """simple docstring"""






   return self._is_overflow


  def __getstate__(						self    :	Dict ):






   """simple docstring"""






   return self.__dict__.copy()



  def __setstate__(						self    :	Dict						,		_UpperCAmelCase    :	Tuple ):






   """simple docstring"""






   self.__dict__.update(_UpperCAmelCase )






'''simple docstring'''




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_   :







  '''simple docstring'''







  def __init__(						self    :	int ):






   """simple docstring"""






   UpperCAmelCase__										=    False


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any						,		_UpperCAmelCase    :	Optional[Any]						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Tuple						,		_UpperCAmelCase    :	Optional[Any] ):






   """simple docstring"""






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


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Union[str, Any] ):






   """simple docstring"""






   self.retriever.index.init_index()


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Union[str, Any] ):






   """simple docstring"""






   del self.retriever
   UpperCAmelCase__										=    False



  def 							SCREAMING_SNAKE_CASE__			(						self    :	Any						,		_UpperCAmelCase    :	Union[str, Any]						,		_UpperCAmelCase    :	Optional[int] ):






   """simple docstring"""






   UpperCAmelCase__							,			UpperCAmelCase__										=    self.retriever._main_retrieve(_UpperCAmelCase						,		_UpperCAmelCase )
   UpperCAmelCase__										=    self.retriever.index.get_doc_dicts(_UpperCAmelCase )
   return doc_ids, retrieved_doc_embeds, doc_dicts

class 						lowerCAmelCase_   ( lowerCamelCase_   ):







  '''simple docstring'''







  def __init__(						self    :	Optional[Any]						,		_UpperCAmelCase    :	List[Any]						,		_UpperCAmelCase    :	Dict						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Any						,		_UpperCAmelCase    :	List[Any]=None ):






   """simple docstring"""






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

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


  def 							SCREAMING_SNAKE_CASE__			(						self    :	Optional[int] ):






   """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 							SCREAMING_SNAKE_CASE__			(						self    :	Tuple						,		_UpperCAmelCase    :	str						,		_UpperCAmelCase    :	Dict ):






   """simple docstring"""






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


  @classmethod
  def 							SCREAMING_SNAKE_CASE__			(						cls    :	str						,		_UpperCAmelCase    :	Optional[Any]						,		_UpperCAmelCase    :	str=None						,		**_UpperCAmelCase    :	Tuple ):






   """simple docstring"""






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


  @classmethod
  def 							SCREAMING_SNAKE_CASE__			(						cls    :	int						,		_UpperCAmelCase    :	Optional[int]						,		_UpperCAmelCase    :	Optional[int]						,		_UpperCAmelCase    :	Union[str, Any]=None						,		**_UpperCAmelCase    :	int ):






   """simple docstring"""






   UpperCAmelCase__										=    kwargs.pop("""config"""						,		_UpperCAmelCase ) or RagConfig.from_pretrained(_UpperCAmelCase						,		**_UpperCAmelCase )
   UpperCAmelCase__										=    RagTokenizer.from_pretrained(_UpperCAmelCase						,		config=_UpperCAmelCase )
   UpperCAmelCase__										=    rag_tokenizer.question_encoder
   UpperCAmelCase__										=    rag_tokenizer.generator

   if indexed_dataset is not None:
    UpperCAmelCase__										=    """custom"""
    UpperCAmelCase__										=    CustomHFIndex(config.retrieval_vector_size						,		_UpperCAmelCase )
   else:
    UpperCAmelCase__										=    cls._build_index(_UpperCAmelCase )

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



  def 							SCREAMING_SNAKE_CASE__			(						self    :	Dict ):






   """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
   UpperCAmelCase__										=    self._build_index(self.config )

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