



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


_UpperCamelCase							    =						logging.get_logger(__name__)

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






class  lowerCamelCase_   (    SCREAMING_SNAKE_CASE_					):
  """simple docstring"""




  a_							 =RetriBertConfig
  a_							 =None
  a_							 ="""retribert"""




  def 						_lowercase					(			self				:     int      ,     _a				:     Union[str, Any]       ) -> List[str]:
    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       )




_UpperCamelCase							    =						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."""       ,       SCREAMING_SNAKE_CASE_       ,       )
class  lowerCamelCase_   (    SCREAMING_SNAKE_CASE_					):
  """simple docstring"""




  def __init__(			self				:     List[str]      ,     _a				:     RetriBertConfig       ) -> None:
    super().__init__(_a       )
    __lowerCamelCase	:	int   	=			config.projection_dim

    __lowerCamelCase	:	Any   	=			BertModel(_a       )
    __lowerCamelCase	:	int   	=			None if config.share_encoders else BertModel(_a       )
    __lowerCamelCase	:	Dict   	=			nn.Dropout(config.hidden_dropout_prob       )
    __lowerCamelCase	:	Union[str, Any]   	=			nn.Linear(config.hidden_size      ,     config.projection_dim      ,     bias=_a       )
    __lowerCamelCase	:	List[str]   	=			nn.Linear(config.hidden_size      ,     config.projection_dim      ,     bias=_a       )

    __lowerCamelCase	:	Dict   	=			nn.CrossEntropyLoss(reduction='mean'       )

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




  def 						_lowercase					(			self				:     Any      ,     _a				:     Any      ,     _a				:     Any      ,     _a				:     Union[str, Any]      ,     _a				:     Any=-1      ,     ) -> Union[str, Any]:
    # 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
      __lowerCamelCase	:	Dict   	=			input_ids.device
      __lowerCamelCase	:	Dict   	=			input_ids.size()
      __lowerCamelCase	:	Dict   	=			torch.zeros(_a      ,     dtype=torch.long      ,     device=_a       )
      __lowerCamelCase	:	List[Any]   	=			[None] * sent_encoder.config.num_hidden_layers
      __lowerCamelCase	:	torch.Tensor   	=			sent_encoder.get_extended_attention_mask(
          _a      ,     _a       )

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

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




  def 						_lowercase					(			self				:     List[Any]      ,     _a				:     Optional[Any]      ,     _a				:     List[Any]=None      ,     _a				:     Union[str, Any]=-1      ,     ) -> Optional[Any]:
    __lowerCamelCase	:	Any   	=			self.embed_sentences_checkpointed(
        _a      ,     _a      ,     self.bert_query      ,     _a      ,     )
    return self.project_query(_a       )




  def 						_lowercase					(			self				:     Any      ,     _a				:     str      ,     _a				:     List[str]=None      ,     _a				:     Tuple=-1      ,     ) -> Union[str, Any]:
    __lowerCamelCase	:	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 						_lowercase					(			self				:     Union[str, Any]      ,     _a				:     torch.LongTensor      ,     _a				:     Optional[torch.FloatTensor]      ,     _a				:     torch.LongTensor      ,     _a				:     Optional[torch.FloatTensor]      ,     _a				:     int = -1      ,     ) -> torch.FloatTensor:
    __lowerCamelCase	:	str   	=			input_ids_query.device
    __lowerCamelCase	:	Optional[int]   	=			self.embed_questions(_a      ,     _a      ,     _a       )
    __lowerCamelCase	:	Union[str, Any]   	=			self.embed_answers(_a      ,     _a      ,     _a       )
    __lowerCamelCase	:	Optional[int]   	=			torch.mm(_a      ,     a_reps.t()       )
    __lowerCamelCase	:	int   	=			self.ce_loss(_a      ,     torch.arange(compare_scores.shape[1]       ).to(_a       )       )
    __lowerCamelCase	:	Any   	=			self.ce_loss(compare_scores.t()      ,     torch.arange(compare_scores.shape[0]       ).to(_a       )       )
    __lowerCamelCase	:	Tuple   	=			(loss_qa + loss_aq) / 2
    return loss











'''simple docstring'''





import math
from timeit import timeit

def 	a_					(							_lowerCAmelCase	)				->				int:
  __lowerCamelCase	:	int   	=			0
  __lowerCamelCase	:	Optional[int]   	=			abs(_lowerCAmelCase	)
  while True:
    __lowerCamelCase	:	List[str]   	=			n // 10
    digits += 1
    if n == 0:
      break
  return digits

def 	a_					(							_lowerCAmelCase	)				->				int:
  return 1 if n == 0 else math.floor(math.log(abs(_lowerCAmelCase	)	,10	) + 1	)

def 	a_					(							_lowerCAmelCase	)				->				int:
  return len(str(abs(_lowerCAmelCase	)	)	)

def 	a_					(							)				->				None:
  from collections.abc import Callable

  def benchmark_a_function(_lowerCAmelCase	,_lowerCAmelCase	) -> None:
    __lowerCamelCase	:	Any   	=			F'{func.__name__}({value})'
    __lowerCamelCase	:	int   	=			timeit(F'__main__.{call}'	,setup='import __main__'	)
    print(F'{call}: {func(_lowerCAmelCase	)} -- {timing} seconds'	)

  for value in (262144, 1125899906842624, 1267650600228229401496703205376):
    for func in (num_digits, num_digits_fast, num_digits_faster):
      benchmark_a_function(_lowerCAmelCase	,_lowerCAmelCase	)
    print()


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   benchmark()






