





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


_snake_case				= logging.get_logger(__name__)

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





class 					lowerCAmelCase							(   lowercase_					):
  __lowerCamelCase		=			RetriBertConfig
  __lowerCamelCase		=			None
  __lowerCamelCase		=			'retribert'







  def   UpperCAmelCase     (			self  :Tuple    ,							_lowercase  :int					):






     '''simple docstring'''





     if isinstance(_lowercase    ,							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(_lowercase    ,							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(_lowercase    ,							nn.LayerNorm					):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0					)
_snake_case				= 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.'							,							lowercase_							,							)
class 					lowerCAmelCase							(   lowercase_					):







  def __init__(			self  :int    ,							_lowercase  :RetriBertConfig					):






     '''simple docstring'''





     super().__init__(_lowercase					)
     lowercase__    =  config.projection_dim

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

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

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







  def   UpperCAmelCase     (			self  :List[Any]    ,							_lowercase  :str    ,							_lowercase  :List[Any]    ,							_lowercase  :List[str]    ,							_lowercase  :Tuple=-1    ,							):






     '''simple docstring'''





     if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
        return sent_encoder(_lowercase    ,							attention_mask=_lowercase					)[1]
     else:
        # prepare implicit variables
        lowercase__    =  input_ids.device
        lowercase__    =  input_ids.size()
        lowercase__    =  torch.zeros(_lowercase    ,							dtype=torch.long    ,							device=_lowercase					)
        lowercase__    =  [None] * sent_encoder.config.num_hidden_layers
        lowercase__    =  sent_encoder.get_extended_attention_mask(
            _lowercase    ,							_lowercase					)

        # define function for checkpointing
        def partial_encode(*_lowercase  :int					):
           lowercase__    =  sent_encoder.encoder(
               inputs[0]    ,							attention_mask=inputs[1]    ,							head_mask=_lowercase    ,							)
           lowercase__    =  encoder_outputs[0]
           lowercase__    =  sent_encoder.pooler(_lowercase					)
           return pooled_output

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







  def   UpperCAmelCase     (			self  :Tuple    ,							_lowercase  :List[str]    ,							_lowercase  :List[str]=None    ,							_lowercase  :List[str]=-1    ,							):






     '''simple docstring'''





     lowercase__    =  self.embed_sentences_checkpointed(
         _lowercase    ,							_lowercase    ,							self.bert_query    ,							_lowercase    ,							)
     return self.project_query(_lowercase					)







  def   UpperCAmelCase     (			self  :Union[str, Any]    ,							_lowercase  :Union[str, Any]    ,							_lowercase  :Optional[int]=None    ,							_lowercase  :Tuple=-1    ,							):






     '''simple docstring'''





     lowercase__    =  self.embed_sentences_checkpointed(
         _lowercase    ,							_lowercase    ,							self.bert_query if self.bert_doc is None else self.bert_doc    ,							_lowercase    ,							)
     return self.project_doc(_lowercase					)







  def   UpperCAmelCase     (			self  :Union[str, Any]    ,							_lowercase  :torch.LongTensor    ,							_lowercase  :Optional[torch.FloatTensor]    ,							_lowercase  :torch.LongTensor    ,							_lowercase  :Optional[torch.FloatTensor]    ,							_lowercase  :int = -1    ,							):






     '''simple docstring'''





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













from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_snake_case				= {"""configuration_dinat""": ["""DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DinatConfig"""]}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _snake_case				= [
      """DINAT_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """DinatForImageClassification""",
      """DinatModel""",
      """DinatPreTrainedModel""",
      """DinatBackbone""",
  ]

if TYPE_CHECKING:
  from .configuration_dinat import DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP, DinatConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_dinat import (
        DINAT_PRETRAINED_MODEL_ARCHIVE_LIST,
        DinatBackbone,
        DinatForImageClassification,
        DinatModel,
        DinatPreTrainedModel,
    )

else:
  import sys

  _snake_case				= _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






