


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


SCREAMING_SNAKE_CASE		:Tuple											=       logging.get_logger(__name__)

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


class       __lowerCAmelCase       (	a   ):






  """simple docstring"""





  _SCREAMING_SNAKE_CASE						      =    RetriBertConfig
  _SCREAMING_SNAKE_CASE						      =    None
  _SCREAMING_SNAKE_CASE						      =    'retribert'



  def    lowerCAmelCase__					(       self    :    str      ,			_lowerCAmelCase    :    List[str]					)				->	Any:




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






SCREAMING_SNAKE_CASE		:str											=       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.'	,					a	,					)
class       __lowerCAmelCase       (	a   ):






  """simple docstring"""





  def __init__(       self    :    Dict      ,			_lowerCAmelCase    :    RetriBertConfig					)				->	None:




     """simple docstring"""
     super().__init__(_lowerCAmelCase					)
     snake_case_         =   config.projection_dim

     snake_case_         =   BertModel(_lowerCAmelCase					)
     snake_case_         =   None if config.share_encoders else BertModel(_lowerCAmelCase					)
     snake_case_         =   nn.Dropout(config.hidden_dropout_prob					)
     snake_case_         =   nn.Linear(config.hidden_size      ,			config.projection_dim      ,			bias=_lowerCAmelCase					)
     snake_case_         =   nn.Linear(config.hidden_size      ,			config.projection_dim      ,			bias=_lowerCAmelCase					)

     snake_case_         =   nn.CrossEntropyLoss(reduction="mean"					)

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



  def    lowerCAmelCase__					(       self    :    Any      ,			_lowerCAmelCase    :    str      ,			_lowerCAmelCase    :    List[str]      ,			_lowerCAmelCase    :    Tuple      ,			_lowerCAmelCase    :    str=-1      ,			)				->	str:




     """simple docstring"""
     # reproduces BERT forward pass with checkpointing
     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
        snake_case_         =   input_ids.device
        snake_case_         =   input_ids.size()
        snake_case_         =   torch.zeros(_lowerCAmelCase      ,			dtype=torch.long      ,			device=_lowerCAmelCase					)
        snake_case_         =   [None] * sent_encoder.config.num_hidden_layers
        snake_case_         =   sent_encoder.get_extended_attention_mask(
            _lowerCAmelCase      ,			_lowerCAmelCase					)

        # define function for checkpointing
        def partial_encode(*_lowerCAmelCase    :    Optional[Any]					):
           snake_case_         =   sent_encoder.encoder(
               inputs[0]      ,			attention_mask=inputs[1]      ,			head_mask=_lowerCAmelCase      ,			)
           snake_case_         =   encoder_outputs[0]
           snake_case_         =   sent_encoder.pooler(_lowerCAmelCase					)
           return pooled_output

        # run embedding layer on everything at once
        snake_case_         =   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
        snake_case_         =   []
        for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size					)					):
           snake_case_         =   embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
           snake_case_         =   extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
           snake_case_         =   checkpoint.checkpoint(_lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase					)
           pooled_output_list.append(_lowerCAmelCase					)
        return torch.cat(_lowerCAmelCase      ,			dim=0					)



  def    lowerCAmelCase__					(       self    :    int      ,			_lowerCAmelCase    :    Dict      ,			_lowerCAmelCase    :    List[str]=None      ,			_lowerCAmelCase    :    Union[str, Any]=-1      ,			)				->	int:




     """simple docstring"""
     snake_case_         =   self.embed_sentences_checkpointed(
         _lowerCAmelCase      ,			_lowerCAmelCase      ,			self.bert_query      ,			_lowerCAmelCase      ,			)
     return self.project_query(_lowerCAmelCase					)



  def    lowerCAmelCase__					(       self    :    int      ,			_lowerCAmelCase    :    int      ,			_lowerCAmelCase    :    List[str]=None      ,			_lowerCAmelCase    :    Union[str, Any]=-1      ,			)				->	Optional[Any]:




     """simple docstring"""
     snake_case_         =   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    lowerCAmelCase__					(       self    :    List[Any]      ,			_lowerCAmelCase    :    torch.LongTensor      ,			_lowerCAmelCase    :    Optional[torch.FloatTensor]      ,			_lowerCAmelCase    :    torch.LongTensor      ,			_lowerCAmelCase    :    Optional[torch.FloatTensor]      ,			_lowerCAmelCase    :    int = -1      ,			)				->	torch.FloatTensor:




     """simple docstring"""
     snake_case_         =   input_ids_query.device
     snake_case_         =   self.embed_questions(_lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase					)
     snake_case_         =   self.embed_answers(_lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase					)
     snake_case_         =   torch.mm(_lowerCAmelCase      ,			a_reps.t()					)
     snake_case_         =   self.ce_loss(_lowerCAmelCase      ,			torch.arange(compare_scores.shape[1]					).to(_lowerCAmelCase					)					)
     snake_case_         =   self.ce_loss(compare_scores.t()      ,			torch.arange(compare_scores.shape[0]					).to(_lowerCAmelCase					)					)
     snake_case_         =   (loss_qa + loss_aq) / 2
     return loss








import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


SCREAMING_SNAKE_CASE		:Tuple											=       logging.get_logger(__name__)


class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def __init__(       self    :    Any					)				->	List[str]:




     """simple docstring"""
     super().__init__()
     if version.parse(torch.__version__					) < version.parse("1.12.0"					):
        raise ImportError(
            F'''You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use '''
            "PytorchGELUTanh. Please upgrade torch."					)



  def    lowerCAmelCase__					(       self    :    Optional[int]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return nn.functional.gelu(_lowerCAmelCase      ,			approximate="tanh"					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    int      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi					) * (input + 0.044_715 * torch.pow(_lowerCAmelCase      ,			3.0					))					))






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def __init__(       self    :    int      ,			_lowerCAmelCase    :    bool = False					)				->	int:




     """simple docstring"""
     super().__init__()
     if use_gelu_python:
        snake_case_         =   self._gelu_python
     else:
        snake_case_         =   nn.functional.gelu



  def    lowerCAmelCase__					(       self    :    Optional[Any]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0					)					))



  def    lowerCAmelCase__					(       self    :    Dict      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return self.act(_lowerCAmelCase					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    Optional[int]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return 0.5 * input * (1.0 + torch.tanh(input * 0.7_978_845_608 * (1.0 + 0.044_715 * input * input)					))






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    int      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return input * torch.sigmoid(1.702 * input					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def __init__(       self    :    List[str]      ,			_lowerCAmelCase    :    float      ,			_lowerCAmelCase    :    float					)				->	Any:




     """simple docstring"""
     if min > max:
        raise ValueError(F'''min should be < max (got min: {min}, max: {max})'''					)

     super().__init__()
     snake_case_         =   min
     snake_case_         =   max



  def    lowerCAmelCase__					(       self    :    Union[str, Any]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return torch.clip(gelu(_lowerCAmelCase					)      ,			self.min      ,			self.max					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def __init__(       self    :    Any					)				->	str:




     """simple docstring"""
     super().__init__()
     snake_case_         =   math.sqrt(2 / math.pi					)



  def    lowerCAmelCase__					(       self    :    Optional[Any]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044_715 * torch.pow(_lowerCAmelCase      ,			3					))					))






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    str      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return nn.functional.silu(_lowerCAmelCase					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def __init__(       self    :    Optional[int]					)				->	List[Any]:




     """simple docstring"""
     super().__init__()
     if version.parse(torch.__version__					) < version.parse("1.9.0"					):
        snake_case_         =   self._mish_python
     else:
        snake_case_         =   nn.functional.mish



  def    lowerCAmelCase__					(       self    :    Tuple      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return input * torch.tanh(nn.functional.softplus(_lowerCAmelCase					)					)



  def    lowerCAmelCase__					(       self    :    Optional[Any]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return self.act(_lowerCAmelCase					)






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    List[str]      ,			_lowerCAmelCase    :    Tensor					)				->	Tensor:




     """simple docstring"""
     return input






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





  def    lowerCAmelCase__					(       self    :    List[Any]      ,			_lowerCAmelCase    :    List[Any]      ,			_lowerCAmelCase    :    Union[str, Any]=0.707_107      ,			_lowerCAmelCase    :    int=0.282_095					)				->	List[str]:




     """simple docstring"""
     snake_case_         =   (input - mu).div(sigma * math.sqrt(2.0					)					)
     return 0.5 * (1.0 + torch.erf(_lowerCAmelCase					))






class       __lowerCAmelCase       (	nn.Module   ):






  """simple docstring"""





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




     """simple docstring"""
     snake_case_         =   nn.functional.relu(_lowerCAmelCase					)
     snake_case_         =   torch.square(_lowerCAmelCase					)
     return squared






class       __lowerCAmelCase       (	a   ):






  """simple docstring"""





  def __getitem__(       self    :    Optional[Any]      ,			_lowerCAmelCase    :    str					)				->	Optional[int]:




     """simple docstring"""
     snake_case_         =   super().__getitem__(_lowerCAmelCase					)
     snake_case_      ,      snake_case_         =   content if isinstance(_lowerCAmelCase      ,			_lowerCAmelCase					) else (content, {})
     return cls(**_lowerCAmelCase					)






SCREAMING_SNAKE_CASE		:Optional[int]											=       {
    '''gelu''': GELUActivation,
    '''gelu_10''': (ClippedGELUActivation, {'''min''': -10, '''max''': 10}),
    '''gelu_fast''': FastGELUActivation,
    '''gelu_new''': NewGELUActivation,
    '''gelu_python''': (GELUActivation, {'''use_gelu_python''': True}),
    '''gelu_pytorch_tanh''': PytorchGELUTanh,
    '''gelu_accurate''': AccurateGELUActivation,
    '''laplace''': LaplaceActivation,
    '''linear''': LinearActivation,
    '''mish''': MishActivation,
    '''quick_gelu''': QuickGELUActivation,
    '''relu''': nn.ReLU,
    '''relu2''': ReLUSquaredActivation,
    '''relu6''': nn.ReLUa,
    '''sigmoid''': nn.Sigmoid,
    '''silu''': SiLUActivation,
    '''swish''': SiLUActivation,
    '''tanh''': nn.Tanh,
}
SCREAMING_SNAKE_CASE		:Optional[int]											=       ClassInstantier(ACTaCLS)



def      _lowerCAmelCase  (							lowerCAmelCase_							:Optional[Any]							)->Union[str, Any]:
   '''simple docstring'''






   if activation_string in ACTaFN:
      return ACTaFN[activation_string]
   else:
      raise KeyError(F'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()							)}'''							)


# For backwards compatibility with: from activations import gelu_python
SCREAMING_SNAKE_CASE		:Tuple											=       get_activation('''gelu_python''')
SCREAMING_SNAKE_CASE		:int											=       get_activation('''gelu_new''')
SCREAMING_SNAKE_CASE		:List[Any]											=       get_activation('''gelu''')
SCREAMING_SNAKE_CASE		:int											=       get_activation('''gelu_fast''')
SCREAMING_SNAKE_CASE		:Tuple											=       get_activation('''quick_gelu''')
SCREAMING_SNAKE_CASE		:Tuple											=       get_activation('''silu''')
SCREAMING_SNAKE_CASE		:Any											=       get_activation('''mish''')



SCREAMING_SNAKE_CASE		:Optional[Any]											=       get_activation('''linear''')




