


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


lowerCamelCase_  :  Union[str, Any]     		=    logging.get_logger(__name__)

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






class  __A							(			a__     ):






 """simple docstring"""




 __lowerCAmelCase					   =    RetriBertConfig
 __lowerCAmelCase					   =    None
 __lowerCAmelCase					   =    """retribert"""


 def  SCREAMING_SNAKE_CASE				(						self					,       __A		)   ->	List[Any]:





     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		)

lowerCamelCase_  :  int     		=    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.",       a__,       )
class  __A							(			a__     ):






 """simple docstring"""




 def __init__(						self					,       __A		)   ->	None:
     super().__init__(lowercase__		)
     a											=config.projection_dim

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

     a											=nn.CrossEntropyLoss(reduction='''mean'''		)

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


 def  SCREAMING_SNAKE_CASE				(						self					,       __A					,       __A					,       __A					,       __A=-1					,       )   ->	Union[str, Any]:





     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
         a											=input_ids.device
         a											=input_ids.size()
         a											=torch.zeros(lowercase__					,       dtype=torch.long					,       device=lowercase__		)
         a											=[None] * sent_encoder.config.num_hidden_layers
         a											=sent_encoder.get_extended_attention_mask(
             lowercase__					,       lowercase__		)

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

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


 def  SCREAMING_SNAKE_CASE				(						self					,       __A					,       __A=None					,       __A=-1					,       )   ->	str:
     a											=self.embed_sentences_checkpointed(
         lowercase__					,       lowercase__					,       self.bert_query					,       lowercase__					,       )
     return self.project_query(lowercase__		)


 def  SCREAMING_SNAKE_CASE				(						self					,       __A					,       __A=None					,       __A=-1					,       )   ->	Dict:
     a											=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  SCREAMING_SNAKE_CASE				(						self					,       __A					,       __A					,       __A					,       __A					,       __A = -1					,       )   ->	torch.FloatTensor:
     a											=input_ids_query.device
     a											=self.embed_questions(lowercase__					,       lowercase__					,       lowercase__		)
     a											=self.embed_answers(lowercase__					,       lowercase__					,       lowercase__		)
     a											=torch.mm(lowercase__					,       a_reps.t()		)
     a											=self.ce_loss(lowercase__					,       torch.arange(compare_scores.shape[1]		).to(lowercase__		)		)
     a											=self.ce_loss(compare_scores.t()					,       torch.arange(compare_scores.shape[0]		).to(lowercase__		)		)
     a											=(loss_qa + loss_aq) / 2
     return loss






'''simple docstring'''

def  _a     (				lowerCAmelCase_ = 4_000_000						):





      """simple docstring"""



      _snake_case		:						Optional[int]         =  1
      _snake_case		:						Tuple         =  2
      _snake_case		:						Optional[Any]         =  0
      while j <= n:
            if j % 2 == 0:
                  total += j
            _snake_case  ,				_snake_case		:						str         =  j, i + j

      return total


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


