






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


SCREAMING_SNAKE_CASE_				      =		logging.get_logger(__name__)

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




class 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







   _A						=   RetriBertConfig
   _A						=   None
   _A						=   'retribert'



   def    __magic_name__    ( self   ,   _A			)    ->   Optional[int]:
    if isinstance(_A   ,   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(_A   ,   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(_A   ,   nn.LayerNorm			):
     module.bias.data.zero_()
     module.weight.data.fill_(1.0			)
SCREAMING_SNAKE_CASE_				      =		r"\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"




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







   """simple docstring"""







   def __init__( self   ,   _A			)    ->   None:
    super().__init__(_A			)
    __a    :	Union[str, Any]									=						config.projection_dim

    __a    :	List[Any]									=						BertModel(_A			)
    __a    :	Optional[Any]									=						None if config.share_encoders else BertModel(_A			)
    __a    :	Optional[int]									=						nn.Dropout(config.hidden_dropout_prob			)
    __a    :	int									=						nn.Linear(config.hidden_size   ,   config.projection_dim   ,   bias=_A			)
    __a    :	Tuple									=						nn.Linear(config.hidden_size   ,   config.projection_dim   ,   bias=_A			)

    __a    :	Union[str, Any]									=						nn.CrossEntropyLoss(reduction='mean'			)

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



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A   ,   _A=-1   ,   )    ->   Optional[int]:
    # reproduces BERT forward pass with checkpointing
    if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
     return sent_encoder(_A   ,   attention_mask=_A			)[1]
    else:
     # prepare implicit variables
     __a    :	int									=						input_ids.device
     __a    :	Union[str, Any]									=						input_ids.size()
     __a    :	Tuple									=						torch.zeros(_A   ,   dtype=torch.long   ,   device=_A			)
     __a    :	Union[str, Any]									=						[None] * sent_encoder.config.num_hidden_layers
     __a    :	torch.Tensor									=						sent_encoder.get_extended_attention_mask(
         _A   ,   _A			)

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

     # run embedding layer on everything at once
     __a    :	Union[str, Any]									=						sent_encoder.embeddings(
         input_ids=_A   ,   position_ids=_A   ,   token_type_ids=_A   ,   inputs_embeds=_A			)
     # run encoding and pooling on one mini-batch at a time
     __a    :	Union[str, Any]									=						[]
     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    :	Union[str, Any]									=						extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
      __a    :	Optional[Any]									=						checkpoint.checkpoint(_A   ,   _A   ,   _A			)
      pooled_output_list.append(_A			)
     return torch.cat(_A   ,   dim=0			)



   def    __magic_name__    ( self   ,   _A   ,   _A=None   ,   _A=-1   ,   )    ->   int:
    __a    :	str									=						self.embed_sentences_checkpointed(
        _A   ,   _A   ,   self.bert_query   ,   _A   ,   )
    return self.project_query(_A			)



   def    __magic_name__    ( self   ,   _A   ,   _A=None   ,   _A=-1   ,   )    ->   Optional[Any]:
    __a    :	Optional[int]									=						self.embed_sentences_checkpointed(
        _A   ,   _A   ,   self.bert_query if self.bert_doc is None else self.bert_doc   ,   _A   ,   )
    return self.project_doc(_A			)



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A   ,   _A   ,   _A = -1   ,   )    ->   torch.FloatTensor:
    __a    :	Any									=						input_ids_query.device
    __a    :	Dict									=						self.embed_questions(_A   ,   _A   ,   _A			)
    __a    :	Any									=						self.embed_answers(_A   ,   _A   ,   _A			)
    __a    :	Optional[Any]									=						torch.mm(_A   ,   a_reps.t()			)
    __a    :	Optional[int]									=						self.ce_loss(_A   ,   torch.arange(compare_scores.shape[1]			).to(_A			)			)
    __a    :	Dict									=						self.ce_loss(compare_scores.t()   ,   torch.arange(compare_scores.shape[0]			).to(_A			)			)
    __a    :	Tuple									=						(loss_qa + loss_aq) / 2
    return loss












'''simple docstring'''


def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__ = 30		):
 __a    :	Tuple									=						exponent + 2
 __a    :	str									=						(1 + 5**0.5) / 2
 __a    :	Any									=						(phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5

 return int(SCREAMING_SNAKE_CASE__		)


if __name__ == "__main__":
  print(F"{solution() = }")




