


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			:						Tuple        =  logging.getLogger(__name__)



class 				A       (			UpperCAmelCase__				):
					'''simple docstring'''






					def __init__(self       :		Optional[int] ,   _UpperCAmelCase       :		Optional[Any] ,   _UpperCAmelCase       :		Tuple ,   _UpperCAmelCase       :		Tuple ,   _UpperCAmelCase       :		Any=None						)		->  Optional[int]:




							"""simple docstring"""


							super().__init__(
							    _UpperCAmelCase ,   question_encoder_tokenizer=_UpperCAmelCase ,   generator_tokenizer=_UpperCAmelCase ,   index=_UpperCAmelCase ,   init_retrieval=_UpperCAmelCase ,   )
							lowercase__	     =						None

					def     lowerCamelCase__	(self       :		Optional[Any] ,   _UpperCAmelCase       :		int						)		->  Union[str, Any]:




							"""simple docstring"""


							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
									lowercase__	     =						self._infer_socket_ifname()
									# avoid clash with the NCCL port
									lowercase__	     =						str(distributed_port + 1						)
									lowercase__	     =						dist.new_group(ranks=_UpperCAmelCase ,   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       :		Optional[int]						)		->  str:




							"""simple docstring"""


							return dist.get_rank(group=self.process_group						) == 0

					def     lowerCamelCase__	(self       :		List[str] ,   _UpperCAmelCase       :		Union[str, Any] ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		Tuple=torch.floataa						)		->  Tuple:




							"""simple docstring"""


							lowercase__	     =						torch.empty(_UpperCAmelCase ,   dtype=_UpperCAmelCase						)
							dist.scatter(_UpperCAmelCase ,   src=0 ,   scatter_list=_UpperCAmelCase ,   group=self.process_group						)
							return target_tensor

					def     lowerCamelCase__	(self       :		List[Any]						)		->  Union[str, Any]:




							"""simple docstring"""


							lowercase__	     =						psutil.net_if_addrs()
							# a hacky way to deal with varying network interface names
							lowercase__	     =						next((addr for addr in addrs if addr.startswith("""e"""						)) ,   _UpperCAmelCase						)
							return ifname


					def     lowerCamelCase__	(self       :		Dict ,   _UpperCAmelCase       :		np.ndarray ,   _UpperCAmelCase       :		int						)		->  Tuple[np.ndarray, List[dict]]:




							"""simple docstring"""


							if not dist.is_initialized():
									lowercase__     ,      lowercase__	     =						self._main_retrieve(_UpperCAmelCase ,   _UpperCAmelCase						)
									return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(_UpperCAmelCase						)

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

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

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

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


'''simple docstring'''






from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)



