



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


lowercase_									=    logging.getLogger(__name__)






class __A     (    A		):



 '''simple docstring'''







 def __init__(self					,  A					,  A					,  A					,  A=None			)       ->	str:


      """simple docstring"""



      super().__init__(
          A					,  question_encoder_tokenizer=A					,  generator_tokenizer=A					,  index=A					,  init_retrieval=A					,  )
      _a           =    None



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


      """simple docstring"""



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



 def    a__    (self					,  A					,  A					,  A=torch.floataa			)       ->	int:


      """simple docstring"""



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



 def    a__    (self			)       ->	Dict:


      """simple docstring"""



      _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'''			))					,  A			)
      return ifname



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


      """simple docstring"""



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

      # 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(A			)]
      dist.gather(torch.tensor(A			)					,  dst=0					,  gather_list=A					,  group=self.process_group			)

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

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








'''simple docstring'''





import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
  import jax.numpy as jnp

  from transformers.models.albert.modeling_flax_albert import (
      FlaxAlbertForMaskedLM,
      FlaxAlbertForMultipleChoice,
      FlaxAlbertForPreTraining,
      FlaxAlbertForQuestionAnswering,
      FlaxAlbertForSequenceClassification,
      FlaxAlbertForTokenClassification,
      FlaxAlbertModel,
  )






class __A     (    unittest.TestCase		):



 '''simple docstring'''







 def __init__(self					,  A					,  A=13					,  A=7					,  A=True					,  A=True					,  A=True					,  A=True					,  A=99					,  A=32					,  A=5					,  A=4					,  A=37					,  A="gelu"					,  A=0.1					,  A=0.1					,  A=512					,  A=16					,  A=2					,  A=0.02					,  A=4					,  )       ->	List[str]:


      """simple docstring"""



      _a           =    parent
      _a           =    batch_size
      _a           =    seq_length
      _a           =    is_training
      _a           =    use_attention_mask
      _a           =    use_token_type_ids
      _a           =    use_labels
      _a           =    vocab_size
      _a           =    hidden_size
      _a           =    num_hidden_layers
      _a           =    num_attention_heads
      _a           =    intermediate_size
      _a           =    hidden_act
      _a           =    hidden_dropout_prob
      _a           =    attention_probs_dropout_prob
      _a           =    max_position_embeddings
      _a           =    type_vocab_size
      _a           =    type_sequence_label_size
      _a           =    initializer_range
      _a           =    num_choices



 def    a__    (self			)       ->	str:


      """simple docstring"""



      _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.vocab_size			)

      _a           =    None
      if self.use_attention_mask:
           _a           =    random_attention_mask([self.batch_size, self.seq_length]			)

      _a           =    None
      if self.use_token_type_ids:
           _a           =    ids_tensor([self.batch_size, self.seq_length]					,  self.type_vocab_size			)

      _a           =    AlbertConfig(
          vocab_size=self.vocab_size					,  hidden_size=self.hidden_size					,  num_hidden_layers=self.num_hidden_layers					,  num_attention_heads=self.num_attention_heads					,  intermediate_size=self.intermediate_size					,  hidden_act=self.hidden_act					,  hidden_dropout_prob=self.hidden_dropout_prob					,  attention_probs_dropout_prob=self.attention_probs_dropout_prob					,  max_position_embeddings=self.max_position_embeddings					,  type_vocab_size=self.type_vocab_size					,  is_decoder=A					,  initializer_range=self.initializer_range					,  )

      return config, input_ids, token_type_ids, attention_mask



 def    a__    (self			)       ->	List[str]:


      """simple docstring"""



      _a           =    self.prepare_config_and_inputs()
      _a    ,       _a    ,       _a    ,       _a           =    config_and_inputs
      _a           =    {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
      return config, inputs_dict






@require_flax
class __A     (    A  ,  unittest.TestCase		):



 '''simple docstring'''







 __lowerCamelCase       :			Optional[int]		=			(
     (
         FlaxAlbertModel,
         FlaxAlbertForPreTraining,
         FlaxAlbertForMaskedLM,
         FlaxAlbertForMultipleChoice,
         FlaxAlbertForQuestionAnswering,
         FlaxAlbertForSequenceClassification,
         FlaxAlbertForTokenClassification,
         FlaxAlbertForQuestionAnswering,
     )
     if is_flax_available()
     else ()
 )



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


      """simple docstring"""



      _a           =    FlaxAlbertModelTester(self			)



 @slow
 def    a__    (self			)       ->	str:


      """simple docstring"""



      for model_class_name in self.all_model_classes:
           _a           =    model_class_name.from_pretrained('''albert-base-v2'''			)
           _a           =    model(np.ones((1, 1)			)			)
           self.assertIsNotNone(A			)






@require_flax
class __A     (    unittest.TestCase		):



 '''simple docstring'''







 @slow
 def    a__    (self			)       ->	Dict:


      """simple docstring"""



      _a           =    FlaxAlbertModel.from_pretrained('''albert-base-v2'''			)
      _a           =    np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]			)
      _a           =    np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
      _a           =    model(A					,  attention_mask=A			)[0]
      _a           =    (1, 11, 768)
      self.assertEqual(output.shape					,  A			)
      _a           =    np.array(
          [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]			)

      self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]					,  A					,  atol=1E-4			)			)



