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   A							(       UpperCAmelCase_  ):
   __UpperCAmelCase				:				Optional[Any]          =    RetriBertConfig
   __UpperCAmelCase				:				Any          =    None
   __UpperCAmelCase				:				Any          =    'retribert'


   def     lowercase_   (self  :		List[Any] ,						__UpperCAmelCase  :		List[str]	)		->       Any:
         """simple docstring"""



         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	)




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.'	,       UpperCAmelCase_	,       )
class   A							(       UpperCAmelCase_  ):


   def __init__(self  :		Any ,						__UpperCAmelCase  :		RetriBertConfig	)		->       None:
         """simple docstring"""



         super().__init__(__UpperCAmelCase	)
         UpperCAmelCase__			=						config.projection_dim

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

         UpperCAmelCase__			=						nn.CrossEntropyLoss(reduction="mean"	)

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


   def     lowercase_   (self  :		Any ,						__UpperCAmelCase  :		str ,						__UpperCAmelCase  :		List[str] ,						__UpperCAmelCase  :		Any ,						__UpperCAmelCase  :		Any=-1 ,						)		->       Tuple:
         """simple docstring"""



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

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

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


   def     lowercase_   (self  :		Any ,						__UpperCAmelCase  :		Dict ,						__UpperCAmelCase  :		List[str]=None ,						__UpperCAmelCase  :		Optional[Any]=-1 ,						)		->       List[Any]:
         """simple docstring"""



         UpperCAmelCase__			=						self.embed_sentences_checkpointed(
             __UpperCAmelCase ,						__UpperCAmelCase ,						self.bert_query ,						__UpperCAmelCase ,						)
         return self.project_query(__UpperCAmelCase	)


   def     lowercase_   (self  :		Optional[Any] ,						__UpperCAmelCase  :		Dict ,						__UpperCAmelCase  :		Union[str, Any]=None ,						__UpperCAmelCase  :		Union[str, Any]=-1 ,						)		->       Optional[int]:
         """simple docstring"""



         UpperCAmelCase__			=						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  :		Optional[int] ,						__UpperCAmelCase  :		torch.LongTensor ,						__UpperCAmelCase  :		Optional[torch.FloatTensor] ,						__UpperCAmelCase  :		torch.LongTensor ,						__UpperCAmelCase  :		Optional[torch.FloatTensor] ,						__UpperCAmelCase  :		int = -1 ,						)		->       torch.FloatTensor:
         """simple docstring"""



         UpperCAmelCase__			=						input_ids_query.device
         UpperCAmelCase__			=						self.embed_questions(__UpperCAmelCase ,						__UpperCAmelCase ,						__UpperCAmelCase	)
         UpperCAmelCase__			=						self.embed_answers(__UpperCAmelCase ,						__UpperCAmelCase ,						__UpperCAmelCase	)
         UpperCAmelCase__			=						torch.mm(__UpperCAmelCase ,						a_reps.t()	)
         UpperCAmelCase__			=						self.ce_loss(__UpperCAmelCase ,						torch.arange(compare_scores.shape[1]	).to(__UpperCAmelCase	)	)
         UpperCAmelCase__			=						self.ce_loss(compare_scores.t() ,						torch.arange(compare_scores.shape[0]	).to(__UpperCAmelCase	)	)
         UpperCAmelCase__			=						(loss_qa + loss_aq) / 2
         return loss




from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase__       							=      logging.get_logger(__name__)

UpperCamelCase__       							=      {
    'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/config.json'
    # See all CPMAnt models at https://huggingface.co/models?filter=cpmant
}





class   A							(       UpperCAmelCase_  ):
   __UpperCAmelCase				:				int          =    'cpmant'


   def __init__(self  :		Optional[Any] ,						__UpperCAmelCase  :		int = 3_0_7_2_0 ,						__UpperCAmelCase  :		int = 4_0_9_6 ,						__UpperCAmelCase  :		int = 3_2 ,						__UpperCAmelCase  :		int = 1_2_8 ,						__UpperCAmelCase  :		int = 1_0_2_4_0 ,						__UpperCAmelCase  :		int = 4_8 ,						__UpperCAmelCase  :		int = 0.0 ,						__UpperCAmelCase  :		int = 5_1_2 ,						__UpperCAmelCase  :		int = 2_0_4_8 ,						__UpperCAmelCase  :		int = 1E-6 ,						__UpperCAmelCase  :		float = 1.0 ,						__UpperCAmelCase  :		int = 3_2 ,						__UpperCAmelCase  :		int = 3_2 ,						__UpperCAmelCase  :		int = 3_2 ,						__UpperCAmelCase  :		bool = True ,						**__UpperCAmelCase  :		Dict ,						)		->       int:
         """simple docstring"""



         super().__init__(**__UpperCAmelCase	)
         UpperCAmelCase__			=						prompt_types
         UpperCAmelCase__			=						prompt_length
         UpperCAmelCase__			=						segment_types
         UpperCAmelCase__			=						hidden_size
         UpperCAmelCase__			=						num_attention_heads
         UpperCAmelCase__			=						dim_head
         UpperCAmelCase__			=						dim_ff
         UpperCAmelCase__			=						num_hidden_layers
         UpperCAmelCase__			=						position_bias_num_buckets
         UpperCAmelCase__			=						position_bias_max_distance
         UpperCAmelCase__			=						dropout_p
         UpperCAmelCase__			=						eps
         UpperCAmelCase__			=						use_cache
         UpperCAmelCase__			=						vocab_size
         UpperCAmelCase__			=						init_std



