
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           =logging.get_logger(__name__)

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





class 							A__	(			__SCREAMING_SNAKE_CASE):
      _UpperCAmelCase       :					List[Any]					 =    RetriBertConfig
      _UpperCAmelCase       :					Union[str, Any]					 =    None
      _UpperCAmelCase       :					Optional[Any]					 =    """retribert"""
      def 		UpperCamelCase__							(   self					,						__magic_name__   ):
       if isinstance(__magic_name__					,						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(__magic_name__					,						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(__magic_name__					,						nn.LayerNorm   ):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0   )


_lowerCamelCase           =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."""						,     __SCREAMING_SNAKE_CASE						,     )
class 							A__	(			__SCREAMING_SNAKE_CASE):
      def __init__(   self					,						__magic_name__   ):
       super().__init__(__magic_name__   )
       lowerCamelCase	:			Any           =   config.projection_dim

       lowerCamelCase	:			str           =   BertModel(__magic_name__   )
       lowerCamelCase	:			Optional[int]           =   None if config.share_encoders else BertModel(__magic_name__   )
       lowerCamelCase	:			Any           =   nn.Dropout(config.hidden_dropout_prob   )
       lowerCamelCase	:			str           =   nn.Linear(config.hidden_size					,						config.projection_dim					,						bias=__magic_name__   )
       lowerCamelCase	:			int           =   nn.Linear(config.hidden_size					,						config.projection_dim					,						bias=__magic_name__   )

       lowerCamelCase	:			int           =   nn.CrossEntropyLoss(reduction="""mean"""   )

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

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

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






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






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_keras_nlp_available,
    is_tensorflow_text_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_lowerCamelCase           ={
    """configuration_gpt2""": ["""GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPT2Config""", """GPT2OnnxConfig"""],
    """tokenization_gpt2""": ["""GPT2Tokenizer"""],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase           =["""GPT2TokenizerFast"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase           =[
          """GPT2_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """GPT2DoubleHeadsModel""",
          """GPT2ForQuestionAnswering""",
          """GPT2ForSequenceClassification""",
          """GPT2ForTokenClassification""",
          """GPT2LMHeadModel""",
          """GPT2Model""",
          """GPT2PreTrainedModel""",
          """load_tf_weights_in_gpt2""",
      ]

try:
      if not is_tf_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase           =[
          """TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """TFGPT2DoubleHeadsModel""",
          """TFGPT2ForSequenceClassification""",
          """TFGPT2LMHeadModel""",
          """TFGPT2MainLayer""",
          """TFGPT2Model""",
          """TFGPT2PreTrainedModel""",
      ]

try:
      if not is_keras_nlp_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase           =["""TFGPT2Tokenizer"""]

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase           =["""FlaxGPT2LMHeadModel""", """FlaxGPT2Model""", """FlaxGPT2PreTrainedModel"""]

if TYPE_CHECKING:
      from .configuration_gpta import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTaConfig, GPTaOnnxConfig
      from .tokenization_gpta import GPTaTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_gpta_fast import GPTaTokenizerFast

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_gpta import (
                GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
                GPTaDoubleHeadsModel,
                GPTaForQuestionAnswering,
                GPTaForSequenceClassification,
                GPTaForTokenClassification,
                GPTaLMHeadModel,
                GPTaModel,
                GPTaPreTrainedModel,
                load_tf_weights_in_gpta,
            )

      try:
            if not is_tf_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tf_gpta import (
                TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
                TFGPTaDoubleHeadsModel,
                TFGPTaForSequenceClassification,
                TFGPTaLMHeadModel,
                TFGPTaMainLayer,
                TFGPTaModel,
                TFGPTaPreTrainedModel,
            )

      try:
            if not is_keras_nlp_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_gpta_tf import TFGPTaTokenizer

      try:
            if not is_flax_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel, FlaxGPTaPreTrainedModel

else:
      import sys

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




