




'''simple docstring'''






def 		UpperCamelCase__      (		__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE		)    ->   str:
      if index == r:
            for j in range(__SCREAMING_SNAKE_CASE		):
                  print(data[j]				,      end=' '		)
            print(' '		)
            return
      #  When no more elements are there to put in data[]
      if i >= n:
            return
      # current is included, put next at next location
      snake_case__       :   Dict	      =    arr[i]
      combination_util(__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      index + 1				,      __SCREAMING_SNAKE_CASE				,      i + 1		)
      # current is excluded, replace it with
      # next (Note that i+1 is passed, but
      # index is not changed)
      combination_util(__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      i + 1		)
      # The main function that prints all combinations
      # of size r in arr[] of size n. This function
      # mainly uses combinationUtil()






def 		UpperCamelCase__      (		__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE		)    ->   Union[str, Any]:
      # A temporary array to store all combination one by one
      snake_case__       :   Optional[Any]	      =    [0] * r
      # Print all combination using temporary array 'data[]'
      combination_util(__SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      __SCREAMING_SNAKE_CASE				,      0				,      __SCREAMING_SNAKE_CASE				,      0		)


if __name__ == "__main__":
      # Driver code to check the function above
      A_			      =		[10, 20, 30, 40, 50]
      print_combination(arr, len(arr), 3)
      # This code is contributed by Ambuj sahu






'''simple docstring'''






import logging
import os
from typing import List, Tuple

import numpy as np
import psutil
import torch
import torch.distributed as dist

from transformers import RagRetriever


A_			      =		logging.getLogger(__name__)






class        lowercase_      (						lowerCAmelCase_							):





     def __init__(     self     :					List[Any]     ,							__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					Tuple     ,							__lowerCamelCase     :					int=None			):
           super().__init__(
               __lowerCamelCase     ,							question_encoder_tokenizer=__lowerCamelCase     ,							generator_tokenizer=__lowerCamelCase     ,							index=__lowerCamelCase     ,							init_retrieval=__lowerCamelCase     ,							)
           snake_case__       :   Optional[int]	      =    None





     def 			_lowerCAmelCase      (     self     :					List[str]     ,							__lowerCamelCase     :					int			):
           logger.info('initializing retrieval'			)

           # initializing a separate process group for retrieval as the default
           # nccl backend doesn't support gather/scatter operations while gloo
           # is too slow to replace nccl for the core gpu communication
           if dist.is_initialized():
                 logger.info('dist initialized'			)
                 # needs to be set manually
                 snake_case__       :   Any	      =    self._infer_socket_ifname()
                 # avoid clash with the NCCL port
                 snake_case__       :   int	      =    str(distributed_port + 1			)
                 snake_case__       :   Any	      =    dist.new_group(ranks=__lowerCamelCase     ,							backend='gloo'			)

           # initialize retriever only on the main worker
           if not dist.is_initialized() or self._is_main():
                 logger.info('dist not initialized / main'			)
                 self.index.init_index()

           # all processes wait untill the retriever is initialized by the main process
           if dist.is_initialized():
                 torch.distributed.barrier(group=self.process_group			)





     def 			_lowerCAmelCase      (     self     :					List[Any]			):
           return dist.get_rank(group=self.process_group			) == 0





     def 			_lowerCAmelCase      (     self     :					Any     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					Union[str, Any]=torch.floataa			):
           snake_case__       :   Optional[int]	      =    torch.empty(__lowerCamelCase     ,							dtype=__lowerCamelCase			)
           dist.scatter(__lowerCamelCase     ,							src=0     ,							scatter_list=__lowerCamelCase     ,							group=self.process_group			)
           return target_tensor





     def 			_lowerCAmelCase      (     self     :					Dict			):
           snake_case__       :   Union[str, Any]	      =    psutil.net_if_addrs()
           # a hacky way to deal with varying network interface names
           snake_case__       :   Any	      =    next((addr for addr in addrs if addr.startswith('e'			))     ,							__lowerCamelCase			)
           return ifname





     def 			_lowerCAmelCase      (     self     :					Tuple     ,							__lowerCamelCase     :					np.ndarray     ,							__lowerCamelCase     :					int			):

           # single GPU training
           if not dist.is_initialized():
                 snake_case__      ,							snake_case__       :   Optional[int]	      =    self._main_retrieve(__lowerCamelCase     ,							__lowerCamelCase			)
                 return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase			)

           # distributed training
           snake_case__       :   Optional[Any]	      =    dist.get_world_size(group=self.process_group			)

           # gather logic
           snake_case__       :   Optional[int]	      =    None
           if self._is_main():
                 snake_case__       :   Optional[int]	      =    [torch.empty(question_hidden_states.shape     ,							dtype=torch.floataa			) for _ in range(__lowerCamelCase			)]
           dist.gather(torch.tensor(__lowerCamelCase			)     ,							dst=0     ,							gather_list=__lowerCamelCase     ,							group=self.process_group			)

           # scatter logic
           snake_case__       :   Union[str, Any]	      =    question_hidden_states.shape[0]
           snake_case__       :   Tuple	      =    []
           snake_case__       :   List[Any]	      =    []
           if self._is_main():
                 assert len(__lowerCamelCase			) == world_size
                 snake_case__      ,							snake_case__       :   Optional[int]	      =    self._main_retrieve(torch.cat(__lowerCamelCase			).numpy()     ,							__lowerCamelCase			)
                 snake_case__      ,							snake_case__       :   Optional[Any]	      =    torch.tensor(__lowerCamelCase			), torch.tensor(__lowerCamelCase			)
                 snake_case__       :   str	      =    self._chunk_tensor(__lowerCamelCase     ,							__lowerCamelCase			)
                 snake_case__       :   Dict	      =    self._chunk_tensor(__lowerCamelCase     ,							__lowerCamelCase			)
           snake_case__       :   Tuple	      =    self._scattered(__lowerCamelCase     ,							[n_queries, n_docs]     ,							target_type=torch.intaa			)
           snake_case__       :   Dict	      =    self._scattered(__lowerCamelCase     ,							[n_queries, n_docs, question_hidden_states.shape[1]]			)

           return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase			)
