


"""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__				:  List[str]						= logging.get_logger(__name__)

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


class 	A_       (     _UpperCAmelCase   ):





  """simple docstring"""

  lowercase		:	Optional[Any]   =						RetriBertConfig
  lowercase		:	Optional[Any]   =						None
  lowercase		:	Dict   =						"retribert"
  def 							lowercase_     (						self  ,					__UpperCAmelCase						)				->					Any:
     if isinstance(__UpperCAmelCase  ,					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(__UpperCAmelCase  ,					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(__UpperCAmelCase  ,					nn.LayerNorm						):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0						)



SCREAMING_SNAKE_CASE__				:  List[Any]						= 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."      ,  _UpperCAmelCase      ,  )
class 	A_       (     _UpperCAmelCase   ):





  """simple docstring"""

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

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

     a   :	List[str]						=    nn.CrossEntropyLoss(reduction='mean'						)

     # Initialize weights and apply final processing
     self.post_init()
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase=-1  ,					)				->					int:
     # reproduces BERT forward pass with checkpointing
     if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
        return sent_encoder(__UpperCAmelCase  ,					attention_mask=__UpperCAmelCase						)[1]
     else:
        # prepare implicit variables
        a   :	List[Any]						=    input_ids.device
        a   :	str						=    input_ids.size()
        a   :	List[Any]						=    torch.zeros(__UpperCAmelCase  ,					dtype=torch.long  ,					device=__UpperCAmelCase						)
        a   :	List[Any]						=    [None] * sent_encoder.config.num_hidden_layers
        a   :	torch.Tensor						=    sent_encoder.get_extended_attention_mask(
            __UpperCAmelCase  ,					__UpperCAmelCase						)

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

        # run embedding layer on everything at once
        a   :	Tuple						=    sent_encoder.embeddings(
            input_ids=__UpperCAmelCase  ,					position_ids=__UpperCAmelCase  ,					token_type_ids=__UpperCAmelCase  ,					inputs_embeds=__UpperCAmelCase						)
        # run encoding and pooling on one mini-batch at a time
        a   :	List[str]						=    []
        for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size						)						):
           a   :	List[Any]						=    embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
           a   :	Dict						=    extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
           a   :	str						=    checkpoint.checkpoint(__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase						)
           pooled_output_list.append(__UpperCAmelCase						)
        return torch.cat(__UpperCAmelCase  ,					dim=0						)
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=-1  ,					)				->					List[str]:
     a   :	Optional[int]						=    self.embed_sentences_checkpointed(
         __UpperCAmelCase  ,					__UpperCAmelCase  ,					self.bert_query  ,					__UpperCAmelCase  ,					)
     return self.project_query(__UpperCAmelCase						)
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=-1  ,					)				->					str:
     a   :	List[Any]						=    self.embed_sentences_checkpointed(
         __UpperCAmelCase  ,					__UpperCAmelCase  ,					self.bert_query if self.bert_doc is None else self.bert_doc  ,					__UpperCAmelCase  ,					)
     return self.project_doc(__UpperCAmelCase						)






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









"""simple docstring"""






import unittest

from transformers import BlenderbotTokenizer, BlenderbotTokenizerFast
from transformers.utils import cached_property


class 	A_       (     unittest.TestCase   ):





  """simple docstring"""

  @cached_property
  def 							lowercase_     (						self						)				->					Optional[Any]:
     return BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B'						)
  @cached_property
  def 							lowercase_     (						self						)				->					Optional[int]:
     return BlenderbotTokenizerFast.from_pretrained('facebook/blenderbot-3B'						)
  def 							lowercase_     (						self						)				->					Union[str, Any]:
     a   :	List[Any]						=    self.tokenizer_ab
     a   :	int						=    ' I am a small frog.'
     a   :	Any						=    tok([src_text]  ,					padding=__UpperCAmelCase  ,					truncation=__UpperCAmelCase						)['input_ids']
     a   :	List[str]						=    tok.batch_decode(__UpperCAmelCase  ,					skip_special_tokens=__UpperCAmelCase  ,					clean_up_tokenization_spaces=__UpperCAmelCase						)[0]
     assert src_text == decoded
  def 							lowercase_     (						self						)				->					Optional[Any]:
     a   :	Optional[int]						=    self.rust_tokenizer_ab
     a   :	List[Any]						=    ' I am a small frog.'
     a   :	Union[str, Any]						=    tok([src_text]  ,					padding=__UpperCAmelCase  ,					truncation=__UpperCAmelCase						)['input_ids']
     a   :	Optional[Any]						=    tok.batch_decode(__UpperCAmelCase  ,					skip_special_tokens=__UpperCAmelCase  ,					clean_up_tokenization_spaces=__UpperCAmelCase						)[0]
     assert src_text == decoded
  def 							lowercase_     (						self						)				->					Tuple:
     assert self.tokenizer_ab.add_prefix_space
     assert self.tokenizer_ab([' Sam', 'Sam']						).input_ids == [[55_02, 2], [55_02, 2]]






  def 							lowercase_     (						self						)				->					Tuple:
     assert self.rust_tokenizer_ab.add_prefix_space
     assert self.rust_tokenizer_ab([' Sam', 'Sam']						).input_ids == [[55_02, 2], [55_02, 2]]





