




'''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,
)






'''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			)
