




'''simple docstring'''





import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


a		:  List[str]   			=			logging.get_logger(__name__)

a		:  Optional[Any]   			=			[
    '''yjernite/retribert-base-uncased''',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]




class     UpperCamelCase					(  snake_case__					):
  a    :List[Any]      					=				RetriBertConfig
  a    :int      					=				None
  a    :List[Any]      					=				'retribert'



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      if isinstance(__lowerCAmelCase		,    nn.Linear   ):
          module.weight.data.normal_(mean=0.0		,    std=self.config.initializer_range   )
          if module.bias is not None:
              module.bias.data.zero_()
      elif isinstance(__lowerCAmelCase		,    nn.Embedding   ):
          module.weight.data.normal_(mean=0.0		,    std=self.config.initializer_range   )
          if module.padding_idx is not None:
              module.weight.data[module.padding_idx].zero_()
      elif isinstance(__lowerCAmelCase		,    nn.LayerNorm   ):
          module.bias.data.zero_()
          module.weight.data.fill_(1.0   )






a		:  Union[str, Any]   			=			R'''

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''




@add_start_docstrings(
    'Bert Based model to embed queries or document for document retrieval.'			,		snake_case__			,		)
class     UpperCamelCase					(  snake_case__					):



  def __init__( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      super().__init__(__lowerCAmelCase   )
      _a							:       Tuple       					=			config.projection_dim

      _a							:       int       					=			BertModel(__lowerCAmelCase   )
      _a							:       int       					=			None if config.share_encoders else BertModel(__lowerCAmelCase   )
      _a							:       Optional[int]       					=			nn.Dropout(config.hidden_dropout_prob   )
      _a							:       Dict       					=			nn.Linear(config.hidden_size		,    config.projection_dim		,    bias=__lowerCAmelCase   )
      _a							:       Any       					=			nn.Linear(config.hidden_size		,    config.projection_dim		,    bias=__lowerCAmelCase   )

      _a							:       Tuple       					=			nn.CrossEntropyLoss(reduction="""mean"""   )

      # Initialize weights and apply final processing
      self.post_init()



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase=-1		,    ):







      '''simple docstring'''


      if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
          return sent_encoder(__lowerCAmelCase		,    attention_mask=__lowerCAmelCase   )[1]
      else:
          # prepare implicit variables
          _a							:       Optional[int]       					=			input_ids.device
          _a							:       Optional[Any]       					=			input_ids.size()
          _a							:       str       					=			torch.zeros(__lowerCAmelCase		,    dtype=torch.long		,    device=__lowerCAmelCase   )
          _a							:       Optional[int]       					=			[None] * sent_encoder.config.num_hidden_layers
          _a							:       torch.Tensor       					=			sent_encoder.get_extended_attention_mask(
              __lowerCAmelCase		,    __lowerCAmelCase   )

          # define function for checkpointing
          def partial_encode(*__lowerCAmelCase   ):
              _a							:       Tuple       					=			sent_encoder.encoder(
                  inputs[0]		,    attention_mask=inputs[1]		,    head_mask=__lowerCAmelCase		,    )
              _a							:       List[str]       					=			encoder_outputs[0]
              _a							:       List[str]       					=			sent_encoder.pooler(__lowerCAmelCase   )
              return pooled_output

          # run embedding layer on everything at once
          _a							:       Optional[Any]       					=			sent_encoder.embeddings(
              input_ids=__lowerCAmelCase		,    position_ids=__lowerCAmelCase		,    token_type_ids=__lowerCAmelCase		,    inputs_embeds=__lowerCAmelCase   )
          # run encoding and pooling on one mini-batch at a time
          _a							:       Optional[int]       					=			[]
          for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size   )   ):
              _a							:       Union[str, Any]       					=			embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
              _a							:       Any       					=			extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
              _a							:       Optional[int]       					=			checkpoint.checkpoint(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   )
              pooled_output_list.append(__lowerCAmelCase   )
          return torch.cat(__lowerCAmelCase		,    dim=0   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase=None		,    __lowerCAmelCase=-1		,    ):







      '''simple docstring'''


      _a							:       Any       					=			self.embed_sentences_checkpointed(
          __lowerCAmelCase		,    __lowerCAmelCase		,    self.bert_query		,    __lowerCAmelCase		,    )
      return self.project_query(__lowerCAmelCase   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase=None		,    __lowerCAmelCase=-1		,    ):







      '''simple docstring'''


      _a							:       List[Any]       					=			self.embed_sentences_checkpointed(
          __lowerCAmelCase		,    __lowerCAmelCase		,    self.bert_query if self.bert_doc is None else self.bert_doc		,    __lowerCAmelCase		,    )
      return self.project_doc(__lowerCAmelCase   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase = -1		,    ):







      '''simple docstring'''


      _a							:       str       					=			input_ids_query.device
      _a							:       Tuple       					=			self.embed_questions(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   )
      _a							:       List[str]       					=			self.embed_answers(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   )
      _a							:       Dict       					=			torch.mm(__lowerCAmelCase		,    a_reps.t()   )
      _a							:       str       					=			self.ce_loss(__lowerCAmelCase		,    torch.arange(compare_scores.shape[1]   ).to(__lowerCAmelCase   )   )
      _a							:       Any       					=			self.ce_loss(compare_scores.t()		,    torch.arange(compare_scores.shape[0]   ).to(__lowerCAmelCase   )   )
      _a							:       List[str]       					=			(loss_qa + loss_aq) / 2
      return loss








'''simple docstring'''





import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
  from .tokenization_mbartaa import MBartaaTokenizer
else:
  a		:  str   			=			None


a		:  List[str]   			=			logging.get_logger(__name__)

a		:  Dict   			=			{'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}

a		:  Optional[Any]   			=			{
    '''vocab_file''': {
        '''facebook/mbart-large-50-one-to-many-mmt''': (
            '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/mbart-large-50-one-to-many-mmt''': (
            '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/tokenizer.json'''
        ),
    },
}

a		:  Any   			=			{
    '''facebook/mbart-large-50-one-to-many-mmt''': 1_0_2_4,
}

# fmt: off
a		:  Dict   			=			['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''', '''af_ZA''', '''az_AZ''', '''bn_IN''', '''fa_IR''', '''he_IL''', '''hr_HR''', '''id_ID''', '''ka_GE''', '''km_KH''', '''mk_MK''', '''ml_IN''', '''mn_MN''', '''mr_IN''', '''pl_PL''', '''ps_AF''', '''pt_XX''', '''sv_SE''', '''sw_KE''', '''ta_IN''', '''te_IN''', '''th_TH''', '''tl_XX''', '''uk_UA''', '''ur_PK''', '''xh_ZA''', '''gl_ES''', '''sl_SI''']




class     UpperCamelCase					(  snake_case__					):
  a    :str      					=				VOCAB_FILES_NAMES
  a    :int      					=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a    :Dict      					=				PRETRAINED_VOCAB_FILES_MAP
  a    :List[str]      					=				['input_ids', 'attention_mask']
  a    :Optional[Any]      					=				MBartaaTokenizer

  a    :List[int]      					=				[]
  a    :List[int]      					=				[]



  def __init__( self		,    __lowerCAmelCase=None		,    __lowerCAmelCase=None		,    __lowerCAmelCase=None		,    __lowerCAmelCase=None		,    __lowerCAmelCase="</s>"		,    __lowerCAmelCase="</s>"		,    __lowerCAmelCase="<s>"		,    __lowerCAmelCase="<unk>"		,    __lowerCAmelCase="<pad>"		,    __lowerCAmelCase="<mask>"		,    **__lowerCAmelCase		,    ):







      '''simple docstring'''


      _a							:       List[str]       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else mask_token

      _a							:       List[str]       					=			kwargs.get("""additional_special_tokens"""		,    []   )
      kwargs["additional_special_tokens"] += [
          code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
      ]

      super().__init__(
          __lowerCAmelCase		,    src_lang=__lowerCAmelCase		,    tgt_lang=__lowerCAmelCase		,    tokenizer_file=__lowerCAmelCase		,    eos_token=__lowerCAmelCase		,    sep_token=__lowerCAmelCase		,    cls_token=__lowerCAmelCase		,    unk_token=__lowerCAmelCase		,    pad_token=__lowerCAmelCase		,    mask_token=__lowerCAmelCase		,    **__lowerCAmelCase		,    )

      _a							:       Optional[int]       					=			vocab_file
      _a							:       int       					=			False if not self.vocab_file else True

      _a							:       str       					=			{
          lang_code: self.convert_tokens_to_ids(__lowerCAmelCase   ) for lang_code in FAIRSEQ_LANGUAGE_CODES
      }

      _a							:       Dict       					=			src_lang if src_lang is not None else """en_XX"""
      _a							:       Tuple       					=			tgt_lang
      _a							:       Tuple       					=			self.lang_code_to_id[self._src_lang]
      self.set_src_lang_special_tokens(self._src_lang   )



  @property
  def 						a_       ( self   ):







      '''simple docstring'''


      return self._src_lang



  @src_lang.setter
  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       int       					=			new_src_lang
      self.set_src_lang_special_tokens(self._src_lang   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase = None   ):







      '''simple docstring'''


      if token_ids_a is None:
          return self.prefix_tokens + token_ids_a + self.suffix_tokens
      # We don't expect to process pairs, but leave the pair logic for API consistency
      return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase = "en_XX"		,    __lowerCAmelCase = None		,    __lowerCAmelCase = "ro_RO"		,    **__lowerCAmelCase		,    ):







      '''simple docstring'''


      _a							:       List[Any]       					=			src_lang
      _a							:       Any       					=			tgt_lang
      return super().prepare_seqaseq_batch(__lowerCAmelCase		,    __lowerCAmelCase		,    **__lowerCAmelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      return self.set_src_lang_special_tokens(self.src_lang   )



  def 						a_       ( self   ):







      '''simple docstring'''


      return self.set_tgt_lang_special_tokens(self.tgt_lang   )



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Union[str, Any]       					=			self.convert_tokens_to_ids(__lowerCAmelCase   )
      _a							:       Optional[Any]       					=			[self.cur_lang_code_id]
      _a							:       int       					=			[self.eos_token_id]

      _a							:       Any       					=			self.convert_ids_to_tokens(self.prefix_tokens   )
      _a							:       Dict       					=			self.convert_ids_to_tokens(self.suffix_tokens   )

      _a							:       Union[str, Any]       					=			processors.TemplateProcessing(
          single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str		,    pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str		,    special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str		,    self.prefix_tokens + self.suffix_tokens   )   )		,    )



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			self.convert_tokens_to_ids(__lowerCAmelCase   )
      _a							:       List[str]       					=			[self.cur_lang_code_id]
      _a							:       Tuple       					=			[self.eos_token_id]

      _a							:       List[Any]       					=			self.convert_ids_to_tokens(self.prefix_tokens   )
      _a							:       int       					=			self.convert_ids_to_tokens(self.suffix_tokens   )

      _a							:       str       					=			processors.TemplateProcessing(
          single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str		,    pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str		,    special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str		,    self.prefix_tokens + self.suffix_tokens   )   )		,    )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    **__lowerCAmelCase   ):







      '''simple docstring'''


      if src_lang is None or tgt_lang is None:
          raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""   )
      _a							:       List[Any]       					=			src_lang
      _a							:       List[str]       					=			self(__lowerCAmelCase		,    add_special_tokens=__lowerCAmelCase		,    return_tensors=__lowerCAmelCase		,    **__lowerCAmelCase   )
      _a							:       Optional[Any]       					=			self.convert_tokens_to_ids(__lowerCAmelCase   )
      _a							:       Tuple       					=			tgt_lang_id
      return inputs



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase = None   ):







      '''simple docstring'''


      if not self.can_save_slow_tokenizer:
          raise ValueError(
              """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
              """tokenizer."""   )

      if not os.path.isdir(__lowerCAmelCase   ):
          logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''   )
          return
      _a							:       Union[str, Any]       					=			os.path.join(
          __lowerCAmelCase		,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )

      if os.path.abspath(self.vocab_file   ) != os.path.abspath(__lowerCAmelCase   ):
          copyfile(self.vocab_file		,    __lowerCAmelCase   )

      return (out_vocab_file,)


