




'''simple docstring'''





import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


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


a		:  List[str]   			=			{'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}

# See all MVP models at https://huggingface.co/models?filter=mvp
a		:  Union[str, Any]   			=			{
    '''vocab_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''',
    },
    '''added_tokens.json''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''',
    },
    '''merges_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''',
    },
}

a		:  Any   			=			{
    '''RUCAIBox/mvp''': 1_0_2_4,
}





@lru_cache()
def UpperCAmelCase						(					):
    _a							:       int       					=			(
        list(range(ord("""!"""	)      ,  ord("""~"""	) + 1	)	) + list(range(ord("""¡"""	)      ,  ord("""¬"""	) + 1	)	) + list(range(ord("""®"""	)      ,  ord("""ÿ"""	) + 1	)	)
    )
    _a							:       Union[str, Any]       					=			bs[:]
    _a							:       Tuple       					=			0
    for b in range(2**8	):
        if b not in bs:
            bs.append(UpperCAmelCase_	)
            cs.append(2**8 + n	)
            n += 1
    _a							:       Any       					=			[chr(UpperCAmelCase_	) for n in cs]
    return dict(zip(UpperCAmelCase_      ,  UpperCAmelCase_	)	)





def UpperCAmelCase						(					UpperCAmelCase_	):
    _a							:       List[Any]       					=			set()
    _a							:       Union[str, Any]       					=			word[0]
    for char in word[1:]:
        pairs.add((prev_char, char)	)
        _a							:       Optional[int]       					=			char
    return pairs





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



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







      '''simple docstring'''


      _a							:       Any       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else bos_token
      _a							:       Optional[Any]       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else eos_token
      _a							:       Optional[Any]       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else sep_token
      _a							:       Dict       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else cls_token
      _a							:       int       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else unk_token
      _a							:       int       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else pad_token

      # Mask token behave like a normal word, i.e. include the space before it
      _a							:       List[str]       					=			AddedToken(__lowerCAmelCase		,    lstrip=__lowerCAmelCase		,    rstrip=__lowerCAmelCase   ) if isinstance(__lowerCAmelCase		,    __lowerCAmelCase   ) else mask_token

      super().__init__(
          errors=__lowerCAmelCase		,    bos_token=__lowerCAmelCase		,    eos_token=__lowerCAmelCase		,    unk_token=__lowerCAmelCase		,    sep_token=__lowerCAmelCase		,    cls_token=__lowerCAmelCase		,    pad_token=__lowerCAmelCase		,    mask_token=__lowerCAmelCase		,    add_prefix_space=__lowerCAmelCase		,    **__lowerCAmelCase		,    )
      with open(__lowerCAmelCase		,    encoding="""utf-8"""   ) as vocab_handle:
          _a							:       Optional[Any]       					=			json.load(__lowerCAmelCase   )
      _a							:       List[str]       					=			{v: k for k, v in self.encoder.items()}
      _a							:       List[Any]       					=			errors  # how to handle errors in decoding
      _a							:       Dict       					=			bytes_to_unicode()
      _a							:       Dict       					=			{v: k for k, v in self.byte_encoder.items()}
      with open(__lowerCAmelCase		,    encoding="""utf-8"""   ) as merges_handle:
          _a							:       Any       					=			merges_handle.read().split("""\n"""   )[1:-1]
      _a							:       int       					=			[tuple(merge.split()   ) for merge in bpe_merges]
      _a							:       Optional[int]       					=			dict(zip(__lowerCAmelCase		,    range(len(__lowerCAmelCase   )   )   )   )
      _a							:       Union[str, Any]       					=			{}
      _a							:       Optional[int]       					=			add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      _a							:       Any       					=			re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""   )



  @property
  def 						a_       ( self   ):







      '''simple docstring'''


      return len(self.encoder   )



  def 						a_       ( self   ):







      '''simple docstring'''


      return dict(self.encoder		,    **self.added_tokens_encoder   )



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      if token in self.cache:
          return self.cache[token]
      _a							:       int       					=			tuple(__lowerCAmelCase   )
      _a							:       List[Any]       					=			get_pairs(__lowerCAmelCase   )

      if not pairs:
          return token

      while True:
          _a							:       Dict       					=			min(__lowerCAmelCase		,    key=lambda __lowerCAmelCase   : self.bpe_ranks.get(__lowerCAmelCase		,    float("""inf"""   )   )   )
          if bigram not in self.bpe_ranks:
              break
          _a					,   _a							:       Union[str, Any]       					=			bigram
          _a							:       str       					=			[]
          _a							:       List[Any]       					=			0
          while i < len(__lowerCAmelCase   ):
              try:
                  _a							:       List[Any]       					=			word.index(__lowerCAmelCase		,    __lowerCAmelCase   )
              except ValueError:
                  new_word.extend(word[i:]   )
                  break
              else:
                  new_word.extend(word[i:j]   )
                  _a							:       Union[str, Any]       					=			j

              if word[i] == first and i < len(__lowerCAmelCase   ) - 1 and word[i + 1] == second:
                  new_word.append(first + second   )
                  i += 2
              else:
                  new_word.append(word[i]   )
                  i += 1
          _a							:       Optional[Any]       					=			tuple(__lowerCAmelCase   )
          _a							:       Union[str, Any]       					=			new_word
          if len(__lowerCAmelCase   ) == 1:
              break
          else:
              _a							:       Optional[Any]       					=			get_pairs(__lowerCAmelCase   )
      _a							:       Union[str, Any]       					=			""" """.join(__lowerCAmelCase   )
      _a							:       int       					=			word
      return word



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       List[Any]       					=			[]
      for token in re.findall(self.pat		,    __lowerCAmelCase   ):
          _a							:       int       					=			"""""".join(
              self.byte_encoder[b] for b in token.encode("""utf-8"""   )   )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
          bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowerCAmelCase   ).split(""" """   )   )
      return bpe_tokens



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      return self.encoder.get(__lowerCAmelCase		,    self.encoder.get(self.unk_token   )   )



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      return self.decoder.get(__lowerCAmelCase   )



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       List[str]       					=			"""""".join(__lowerCAmelCase   )
      _a							:       int       					=			bytearray([self.byte_decoder[c] for c in text]   ).decode("""utf-8"""		,    errors=self.errors   )
      return text



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







      '''simple docstring'''


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

      with open(__lowerCAmelCase		,    """w"""		,    encoding="""utf-8"""   ) as f:
          f.write(json.dumps(self.encoder		,    indent=2		,    sort_keys=__lowerCAmelCase		,    ensure_ascii=__lowerCAmelCase   ) + """\n"""   )

      _a							:       Optional[Any]       					=			0
      with open(__lowerCAmelCase		,    """w"""		,    encoding="""utf-8"""   ) as writer:
          writer.write("""#version: 0.2\n"""   )
          for bpe_tokens, token_index in sorted(self.bpe_ranks.items()		,    key=lambda __lowerCAmelCase   : kv[1]   ):
              if index != token_index:
                  logger.warning(
                      f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
                      """ Please check that the tokenizer is not corrupted!"""   )
                  _a							:       Optional[Any]       					=			token_index
              writer.write(""" """.join(__lowerCAmelCase   ) + """\n"""   )
              index += 1

      return vocab_file, merge_file



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







      '''simple docstring'''


      if token_ids_a is None:
          return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      _a							:       Union[str, Any]       					=			[self.cls_token_id]
      _a							:       Union[str, Any]       					=			[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep



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







      '''simple docstring'''


      if already_has_special_tokens:
          return super().get_special_tokens_mask(
              token_ids_a=__lowerCAmelCase		,    token_ids_a=__lowerCAmelCase		,    already_has_special_tokens=__lowerCAmelCase   )

      if token_ids_a is None:
          return [1] + ([0] * len(__lowerCAmelCase   )) + [1]
      return [1] + ([0] * len(__lowerCAmelCase   )) + [1, 1] + ([0] * len(__lowerCAmelCase   )) + [1]



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







      '''simple docstring'''


      _a							:       Tuple       					=			[self.sep_token_id]
      _a							:       Any       					=			[self.cls_token_id]

      if token_ids_a is None:
          return len(cls + token_ids_a + sep   ) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep   ) * [0]



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







      '''simple docstring'''


      _a							:       Dict       					=			kwargs.pop("""add_prefix_space"""		,    self.add_prefix_space   )
      if (is_split_into_words or add_prefix_space) and (len(__lowerCAmelCase   ) > 0 and not text[0].isspace()):
          _a							:       str       					=			""" """ + text
      return (text, kwargs)








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


