



"""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


UpperCamelCase     =							logging.getLogger(__name__)






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			def __init__(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__=None		)      ->	Optional[Any]:
				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__											=					None


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__		)      ->	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
					A__											=					self._infer_socket_ifname()
					# avoid clash with the NCCL port
					A__											=					str(distributed_port + 1		)
					A__											=					dist.new_group(ranks=SCREAMING_SNAKE_CASE__						,	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   snake_case__	(      self		)      ->	str:
				return dist.get_rank(group=self.process_group		) == 0


			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__=torch.floataa		)      ->	int:
				A__											=					torch.empty(SCREAMING_SNAKE_CASE__						,	dtype=SCREAMING_SNAKE_CASE__		)
				dist.scatter(SCREAMING_SNAKE_CASE__						,	src=0						,	scatter_list=SCREAMING_SNAKE_CASE__						,	group=self.process_group		)
				return target_tensor


			def   snake_case__	(      self		)      ->	List[Any]:
				A__											=					psutil.net_if_addrs()
				# a hacky way to deal with varying network interface names
				A__											=					next((addr for addr in addrs if addr.startswith("e"		))						,	SCREAMING_SNAKE_CASE__		)
				return ifname







			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)      ->	Tuple[np.ndarray, List[dict]]:

				# single GPU training
				if not dist.is_initialized():
					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__		)

				# distributed training
				A__											=					dist.get_world_size(group=self.process_group		)

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

				# scatter logic
				A__											=					question_hidden_states.shape[0]
				A__											=					[]
				A__											=					[]
				if self._is_main():
					assert len(SCREAMING_SNAKE_CASE__		) == world_size
					A__							,							A__											=					self._main_retrieve(torch.cat(SCREAMING_SNAKE_CASE__		).numpy()						,	SCREAMING_SNAKE_CASE__		)
					A__							,							A__											=					torch.tensor(SCREAMING_SNAKE_CASE__		), torch.tensor(SCREAMING_SNAKE_CASE__		)
					A__											=					self._chunk_tensor(SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)
					A__											=					self._chunk_tensor(SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)
				A__											=					self._scattered(SCREAMING_SNAKE_CASE__						,	[n_queries, n_docs]						,	target_type=torch.intaa		)
				A__											=					self._scattered(SCREAMING_SNAKE_CASE__						,	[n_queries, n_docs, question_hidden_states.shape[1]]		)

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












"""simple docstring"""
from __future__ import annotations






def       __UpperCamelCase						(		snake_case__ , snake_case__       ):
	if len(snake_case__       ) == 0:
		return False
	A_		:    Union[str, Any]						     = len(snake_case__       ) // 2
	if a_list[midpoint] == item:
		return True
	if item < a_list[midpoint]:
		return binary_search(a_list[:midpoint] , snake_case__       )
	else:
		return binary_search(a_list[midpoint + 1 :] , snake_case__       )


if __name__ == "__main__":
							_lowerCAmelCase       =				input("Enter numbers separated by comma:\n").strip()
							_lowerCAmelCase       =				[int(item.strip()) for item in user_input.split(",")]
							_lowerCAmelCase       =				int(input("Enter the number to be found in the list:\n").strip())
							_lowerCAmelCase       =				"" if binary_search(sequence, target) else "not "
							print(F'{target} was {not_str}found in {sequence}')

