




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

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



class  _snake_case				(							A__       ):

				'''simple docstring'''




				UpperCamelCase__		     =RetriBertConfig
				UpperCamelCase__		     =None
				UpperCamelCase__		     ="""retribert"""





				def 				snake_case_ (							self      :  List[str]					,							snake_case      :  Union[str, Any]     ):
								if isinstance(snake_case					,							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(snake_case					,							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(snake_case					,							nn.LayerNorm     ):
												module.bias.data.zero_()
												module.weight.data.fill_(1.0     )


__lowerCamelCase								=						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  _snake_case				(							A__       ):

				'''simple docstring'''




				def __init__(							self      :  List[str]					,							snake_case      :  RetriBertConfig     ):
								super().__init__(snake_case     )
								UpperCAmelCase_					:Optional[int]      			=      config.projection_dim

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

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

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





				def 				snake_case_ (							self      :  Optional[int]					,							snake_case      :  List[str]					,							snake_case      :  Tuple					,							snake_case      :  List[str]					,							snake_case      :  Optional[Any]=-1					,							):
								# reproduces BERT forward pass with checkpointing
								if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
												return sent_encoder(snake_case					,							attention_mask=snake_case     )[1]
								else:
												# prepare implicit variables
												UpperCAmelCase_					:int      			=      input_ids.device
												UpperCAmelCase_					:Union[str, Any]      			=      input_ids.size()
												UpperCAmelCase_					:List[Any]      			=      torch.zeros(snake_case					,							dtype=torch.long					,							device=snake_case     )
												UpperCAmelCase_					:List[str]      			=      [None] * sent_encoder.config.num_hidden_layers
												UpperCAmelCase_					:torch.Tensor      			=      sent_encoder.get_extended_attention_mask(
												    snake_case					,							snake_case     )

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

												# run embedding layer on everything at once
												UpperCAmelCase_					:List[Any]      			=      sent_encoder.embeddings(
												    input_ids=snake_case					,							position_ids=snake_case					,							token_type_ids=snake_case					,							inputs_embeds=snake_case     )
												# run encoding and pooling on one mini-batch at a time
												UpperCAmelCase_					:List[str]      			=      []
												for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size     )     ):
																UpperCAmelCase_					:Optional[Any]      			=      embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																UpperCAmelCase_					:Any      			=      extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																UpperCAmelCase_					:Tuple      			=      checkpoint.checkpoint(snake_case					,							snake_case					,							snake_case     )
																pooled_output_list.append(snake_case     )
												return torch.cat(snake_case					,							dim=0     )





				def 				snake_case_ (							self      :  str					,							snake_case      :  List[Any]					,							snake_case      :  List[str]=None					,							snake_case      :  Union[str, Any]=-1					,							):
								UpperCAmelCase_					:int      			=      self.embed_sentences_checkpointed(
								    snake_case					,							snake_case					,							self.bert_query					,							snake_case					,							)
								return self.project_query(snake_case     )





				def 				snake_case_ (							self      :  Optional[int]					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[int]=None					,							snake_case      :  str=-1					,							):
								UpperCAmelCase_					:str      			=      self.embed_sentences_checkpointed(
								    snake_case					,							snake_case					,							self.bert_query if self.bert_doc is None else self.bert_doc					,							snake_case					,							)
								return self.project_doc(snake_case     )





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








"""simple docstring"""

from typing import TYPE_CHECKING

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


__lowerCamelCase								=						{
    "configuration_bart": ["BART_PRETRAINED_CONFIG_ARCHIVE_MAP", "BartConfig", "BartOnnxConfig"],
    "tokenization_bart": ["BartTokenizer"],
}

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

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__lowerCamelCase								=						[
						    "BART_PRETRAINED_MODEL_ARCHIVE_LIST",
						    "BartForCausalLM",
						    "BartForConditionalGeneration",
						    "BartForQuestionAnswering",
						    "BartForSequenceClassification",
						    "BartModel",
						    "BartPretrainedModel",
						    "PretrainedBartModel",
						]

try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__lowerCamelCase								=						[
						    "TFBartForConditionalGeneration",
						    "TFBartForSequenceClassification",
						    "TFBartModel",
						    "TFBartPretrainedModel",
						]

try:
						if not is_flax_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						__lowerCamelCase								=						[
						    "FlaxBartDecoderPreTrainedModel",
						    "FlaxBartForCausalLM",
						    "FlaxBartForConditionalGeneration",
						    "FlaxBartForQuestionAnswering",
						    "FlaxBartForSequenceClassification",
						    "FlaxBartModel",
						    "FlaxBartPreTrainedModel",
						]

if TYPE_CHECKING:
						from .configuration_bart import BART_PRETRAINED_CONFIG_ARCHIVE_MAP, BartConfig, BartOnnxConfig
						from .tokenization_bart import BartTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_bart_fast import BartTokenizerFast

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_bart import (
												    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
												    BartForCausalLM,
												    BartForConditionalGeneration,
												    BartForQuestionAnswering,
												    BartForSequenceClassification,
												    BartModel,
												    BartPretrainedModel,
												    PretrainedBartModel,
												)

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_bart import (
												    TFBartForConditionalGeneration,
												    TFBartForSequenceClassification,
												    TFBartModel,
												    TFBartPretrainedModel,
												)

						try:
												if not is_flax_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_flax_bart import (
												    FlaxBartDecoderPreTrainedModel,
												    FlaxBartForCausalLM,
												    FlaxBartForConditionalGeneration,
												    FlaxBartForQuestionAnswering,
												    FlaxBartForSequenceClassification,
												    FlaxBartModel,
												    FlaxBartPreTrainedModel,
												)

else:
						import sys

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


