




'''simple docstring'''






import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


A_			      =		logging.getLogger(__name__)






@dataclass
class        lowercase_      :
     A_											=			42
     A_											=			42
     A_											=			42






@dataclass
class        lowercase_      :
     A_											=			42
     A_											=			42
     A_											=			None
     A_											=			None






class        lowercase_      (						lowerCAmelCase_							):
     A_											=			"train"
     A_											=			"dev"
     A_											=			"test"






class        lowercase_      :





     @staticmethod
     def 			_lowerCAmelCase      (     __lowerCamelCase     :					Any     ,							__lowerCamelCase     :					Union[Split, str]			):
           raise NotImplementedError





     @staticmethod
     def 			_lowerCAmelCase      (     __lowerCamelCase     :					str			):
           raise NotImplementedError





     @staticmethod
     def 			_lowerCAmelCase      (     __lowerCamelCase     :					List[InputExample]     ,							__lowerCamelCase     :					List[str]     ,							__lowerCamelCase     :					int     ,							__lowerCamelCase     :					PreTrainedTokenizer     ,							__lowerCamelCase     :					Any=False     ,							__lowerCamelCase     :					Dict="[CLS]"     ,							__lowerCamelCase     :					int=1     ,							__lowerCamelCase     :					List[str]="[SEP]"     ,							__lowerCamelCase     :					int=False     ,							__lowerCamelCase     :					Optional[int]=False     ,							__lowerCamelCase     :					str=0     ,							__lowerCamelCase     :					int=0     ,							__lowerCamelCase     :					Optional[int]=-100     ,							__lowerCamelCase     :					Optional[Any]=0     ,							__lowerCamelCase     :					int=True     ,							):
           snake_case__       :   Optional[Any]	      =    {label: i for i, label in enumerate(__lowerCamelCase			)}

           snake_case__       :   List[Any]	      =    []
           for ex_index, example in enumerate(__lowerCamelCase			):
                 if ex_index % 10000 == 0:
                       logger.info('Writing example %d of %d'     ,							__lowerCamelCase     ,							len(__lowerCamelCase			)			)

                 snake_case__       :   str	      =    []
                 snake_case__       :   str	      =    []
                 for word, label in zip(example.words     ,							example.labels			):
                       snake_case__       :   int	      =    tokenizer.tokenize(__lowerCamelCase			)

                       # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
                       if len(__lowerCamelCase			) > 0:
                             tokens.extend(__lowerCamelCase			)
                             # Use the real label id for the first token of the word, and padding ids for the remaining tokens
                             label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__lowerCamelCase			) - 1)			)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
                 snake_case__       :   Optional[int]	      =    tokenizer.num_special_tokens_to_add()
                 if len(__lowerCamelCase			) > max_seq_length - special_tokens_count:
                       snake_case__       :   Tuple	      =    tokens[: (max_seq_length - special_tokens_count)]
                       snake_case__       :   Any	      =    label_ids[: (max_seq_length - special_tokens_count)]

                 # The convention in BERT is:
                 # (a) For sequence pairs:
                 #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
                 #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
                 # (b) For single sequences:
                 #  tokens:   [CLS] the dog is hairy . [SEP]
                 #  type_ids:   0   0   0   0  0     0   0
                 #
                 # Where "type_ids" are used to indicate whether this is the first
                 # sequence or the second sequence. The embedding vectors for `type=0` and
                 # `type=1` were learned during pre-training and are added to the wordpiece
                 # embedding vector (and position vector). This is not *strictly* necessary
                 # since the [SEP] token unambiguously separates the sequences, but it makes
                 # it easier for the model to learn the concept of sequences.
                 #
                 # For classification tasks, the first vector (corresponding to [CLS]) is
                 # used as the "sentence vector". Note that this only makes sense because
                 # the entire model is fine-tuned.
                 tokens += [sep_token]
                 label_ids += [pad_token_label_id]
                 if sep_token_extra:
                       # roberta uses an extra separator b/w pairs of sentences
                       tokens += [sep_token]
                       label_ids += [pad_token_label_id]
                 snake_case__       :   Tuple	      =    [sequence_a_segment_id] * len(__lowerCamelCase			)

                 if cls_token_at_end:
                       tokens += [cls_token]
                       label_ids += [pad_token_label_id]
                       segment_ids += [cls_token_segment_id]
                 else:
                       snake_case__       :   Union[str, Any]	      =    [cls_token] + tokens
                       snake_case__       :   Tuple	      =    [pad_token_label_id] + label_ids
                       snake_case__       :   Dict	      =    [cls_token_segment_id] + segment_ids

                 snake_case__       :   Tuple	      =    tokenizer.convert_tokens_to_ids(__lowerCamelCase			)

                 # The mask has 1 for real tokens and 0 for padding tokens. Only real
                 # tokens are attended to.
                 snake_case__       :   List[Any]	      =    [1 if mask_padding_with_zero else 0] * len(__lowerCamelCase			)

                 # Zero-pad up to the sequence length.
                 snake_case__       :   int	      =    max_seq_length - len(__lowerCamelCase			)
                 if pad_on_left:
                       snake_case__       :   List[Any]	      =    ([pad_token] * padding_length) + input_ids
                       snake_case__       :   Union[str, Any]	      =    ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
                       snake_case__       :   List[Any]	      =    ([pad_token_segment_id] * padding_length) + segment_ids
                       snake_case__       :   str	      =    ([pad_token_label_id] * padding_length) + label_ids
                 else:
                       input_ids += [pad_token] * padding_length
                       input_mask += [0 if mask_padding_with_zero else 1] * padding_length
                       segment_ids += [pad_token_segment_id] * padding_length
                       label_ids += [pad_token_label_id] * padding_length

                 assert len(__lowerCamelCase			) == max_seq_length
                 assert len(__lowerCamelCase			) == max_seq_length
                 assert len(__lowerCamelCase			) == max_seq_length
                 assert len(__lowerCamelCase			) == max_seq_length

                 if ex_index < 5:
                       logger.info('*** Example ***'			)
                       logger.info('guid: %s'     ,							example.guid			)
                       logger.info('tokens: %s'     ,							' '.join([str(__lowerCamelCase			) for x in tokens]			)			)
                       logger.info('input_ids: %s'     ,							' '.join([str(__lowerCamelCase			) for x in input_ids]			)			)
                       logger.info('input_mask: %s'     ,							' '.join([str(__lowerCamelCase			) for x in input_mask]			)			)
                       logger.info('segment_ids: %s'     ,							' '.join([str(__lowerCamelCase			) for x in segment_ids]			)			)
                       logger.info('label_ids: %s'     ,							' '.join([str(__lowerCamelCase			) for x in label_ids]			)			)

                 if "token_type_ids" not in tokenizer.model_input_names:
                       snake_case__       :   int	      =    None

                 features.append(
                     InputFeatures(
                         input_ids=__lowerCamelCase     ,							attention_mask=__lowerCamelCase     ,							token_type_ids=__lowerCamelCase     ,							label_ids=__lowerCamelCase			)			)
           return features


if is_torch_available():
      import torch
      from torch import nn
      from torch.utils.data import Dataset






      class        lowercase_      (						lowerCAmelCase_							):
           A_											=			42
           A_											=			nn.CrossEntropyLoss().ignore_index





           def __init__(     self     :					List[Any]     ,							__lowerCamelCase     :					TokenClassificationTask     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					PreTrainedTokenizer     ,							__lowerCamelCase     :					List[str]     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					Optional[int] = None     ,							__lowerCamelCase     :					int=False     ,							__lowerCamelCase     :					Split = Split.train     ,							):
                 # Load data features from cache or dataset file
                 snake_case__       :   Union[str, Any]	      =    os.path.join(
                     __lowerCamelCase     ,							'cached_{}_{}_{}'.format(mode.value     ,							tokenizer.__class__.__name__     ,							str(__lowerCamelCase			)			)     ,							)

                 # Make sure only the first process in distributed training processes the dataset,
                 # and the others will use the cache.
                 snake_case__       :   List[str]	      =    cached_features_file + '.lock'
                 with FileLock(__lowerCamelCase			):
                       if os.path.exists(__lowerCamelCase			) and not overwrite_cache:
                             logger.info(F"Loading features from cached file {cached_features_file}"			)
                             snake_case__       :   List[Any]	      =    torch.load(__lowerCamelCase			)
                       else:
                             logger.info(F"Creating features from dataset file at {data_dir}"			)
                             snake_case__       :   str	      =    token_classification_task.read_examples_from_file(__lowerCamelCase     ,							__lowerCamelCase			)
                             # TODO clean up all this to leverage built-in features of tokenizers
                             snake_case__       :   Tuple	      =    token_classification_task.convert_examples_to_features(
                                 __lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase     ,							cls_token_at_end=bool(model_type in ['xlnet']			)     ,							cls_token=tokenizer.cls_token     ,							cls_token_segment_id=2 if model_type in ['xlnet'] else 0     ,							sep_token=tokenizer.sep_token     ,							sep_token_extra=__lowerCamelCase     ,							pad_on_left=bool(tokenizer.padding_side == 'left'			)     ,							pad_token=tokenizer.pad_token_id     ,							pad_token_segment_id=tokenizer.pad_token_type_id     ,							pad_token_label_id=self.pad_token_label_id     ,							)
                             logger.info(F"Saving features into cached file {cached_features_file}"			)
                             torch.save(self.features     ,							__lowerCamelCase			)





           def __len__(     self     :					Optional[int]			):
                 return len(self.features			)





           def __getitem__(     self     :					List[Any]     ,							__lowerCamelCase     :					Any			):
                 return self.features[i]


if is_tf_available():
      import tensorflow as tf






      class        lowercase_      :
           A_											=			42
           A_											=			-1_0_0





           def __init__(     self     :					Tuple     ,							__lowerCamelCase     :					TokenClassificationTask     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					PreTrainedTokenizer     ,							__lowerCamelCase     :					List[str]     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					Optional[int] = None     ,							__lowerCamelCase     :					List[str]=False     ,							__lowerCamelCase     :					Split = Split.train     ,							):
                 snake_case__       :   List[str]	      =    token_classification_task.read_examples_from_file(__lowerCamelCase     ,							__lowerCamelCase			)
                 # TODO clean up all this to leverage built-in features of tokenizers
                 snake_case__       :   Tuple	      =    token_classification_task.convert_examples_to_features(
                     __lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase     ,							cls_token_at_end=bool(model_type in ['xlnet']			)     ,							cls_token=tokenizer.cls_token     ,							cls_token_segment_id=2 if model_type in ['xlnet'] else 0     ,							sep_token=tokenizer.sep_token     ,							sep_token_extra=__lowerCamelCase     ,							pad_on_left=bool(tokenizer.padding_side == 'left'			)     ,							pad_token=tokenizer.pad_token_id     ,							pad_token_segment_id=tokenizer.pad_token_type_id     ,							pad_token_label_id=self.pad_token_label_id     ,							)

                 def gen():
                       for ex in self.features:
                             if ex.token_type_ids is None:
                                   yield (
                                       {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                                       ex.label_ids,
                                   )
                             else:
                                   yield (
                                       {
                                           "input_ids": ex.input_ids,
                                           "attention_mask": ex.attention_mask,
                                           "token_type_ids": ex.token_type_ids,
                                       },
                                       ex.label_ids,
                                   )

                 if "token_type_ids" not in tokenizer.model_input_names:
                       snake_case__       :   List[Any]	      =    tf.data.Dataset.from_generator(
                           __lowerCamelCase     ,							({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)     ,							(
                               {'input_ids': tf.TensorShape([None]			), 'attention_mask': tf.TensorShape([None]			)},
                               tf.TensorShape([None]			),
                           )     ,							)
                 else:
                       snake_case__       :   Any	      =    tf.data.Dataset.from_generator(
                           __lowerCamelCase     ,							({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa)     ,							(
                               {
                                   'input_ids': tf.TensorShape([None]			),
                                   'attention_mask': tf.TensorShape([None]			),
                                   'token_type_ids': tf.TensorShape([None]			),
                               },
                               tf.TensorShape([None]			),
                           )     ,							)





           def 			_lowerCAmelCase      (     self     :					Optional[Any]			):
                 snake_case__       :   Tuple	      =    self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features			)			)			)

                 return self.dataset





           def __len__(     self     :					Union[str, Any]			):
                 return len(self.features			)





           def __getitem__(     self     :					Union[str, Any]     ,							__lowerCamelCase     :					Any			):
                 return self.features[i]






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