





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


_snake_case	:						Dict					=					logging.get_logger(__name__)

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






class    _UpperCAmelCase  (      _lowercase					):
					UpperCamelCase						=				RetriBertConfig
					UpperCamelCase						=				None
					UpperCamelCase						=				'''retribert'''


					def       lowerCamelCase			(   self     :Optional[int]	,			__UpperCamelCase     :Union[str, 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						)







_snake_case	:						Tuple					=					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.'''	,				_lowercase	,				)
class    _UpperCAmelCase  (      _lowercase					):


					def __init__(   self     :Any	,			__UpperCamelCase     :RetriBertConfig						):
												super().__init__(UpperCamelCase__						)
												A						=    config.projection_dim

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

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

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


					def       lowerCamelCase			(   self     :Any	,			__UpperCamelCase     :Optional[Any]	,			__UpperCamelCase     :Optional[Any]	,			__UpperCamelCase     :List[str]	,			__UpperCamelCase     :Optional[int]=-1	,			):
												# 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						=    input_ids.device
																			A						=    input_ids.size()
																			A						=    torch.zeros(UpperCamelCase__	,			dtype=torch.long	,			device=UpperCamelCase__						)
																			A						=    [None] * sent_encoder.config.num_hidden_layers
																			A						=    sent_encoder.get_extended_attention_mask(
																			    UpperCamelCase__	,			UpperCamelCase__						)

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

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


					def       lowerCamelCase			(   self     :Tuple	,			__UpperCamelCase     :Any	,			__UpperCamelCase     :Optional[int]=None	,			__UpperCamelCase     :Optional[int]=-1	,			):
												A						=    self.embed_sentences_checkpointed(
												    UpperCamelCase__	,			UpperCamelCase__	,			self.bert_query	,			UpperCamelCase__	,			)
												return self.project_query(UpperCamelCase__						)


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










'''simple docstring'''







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


_A      :     Union[str, Any]       	=logging.get_logger(__name__)

_A      :     Tuple       	={
    '''tau/splinter-base''': '''https://huggingface.co/tau/splinter-base/resolve/main/config.json''',
    '''tau/splinter-base-qass''': '''https://huggingface.co/tau/splinter-base-qass/resolve/main/config.json''',
    '''tau/splinter-large''': '''https://huggingface.co/tau/splinter-large/resolve/main/config.json''',
    '''tau/splinter-large-qass''': '''https://huggingface.co/tau/splinter-large-qass/resolve/main/config.json''',
    # See all Splinter models at https://huggingface.co/models?filter=splinter
}

class _lowercase      (							_lowercase						):
							a							 =			"""splinter"""




							def __init__(				self:							List[str]     ,				UpperCamelCase__:							List[Any]=30_522     ,				UpperCamelCase__:							Union[str, Any]=768     ,				UpperCamelCase__:							str=12     ,				UpperCamelCase__:							Dict=12     ,				UpperCamelCase__:							Tuple=3_072     ,				UpperCamelCase__:							Optional[int]="gelu"     ,				UpperCamelCase__:							Optional[int]=0.1     ,				UpperCamelCase__:							str=0.1     ,				UpperCamelCase__:							List[Any]=512     ,				UpperCamelCase__:							List[str]=2     ,				UpperCamelCase__:							Any=0.02     ,				UpperCamelCase__:							Optional[Any]=1e-12     ,				UpperCamelCase__:							Dict=True     ,				UpperCamelCase__:							str=0     ,				UpperCamelCase__:							int=104     ,				**UpperCamelCase__:							Any     ,				):
														super().__init__(pad_token_id=UpperCamelCase__     ,				**UpperCamelCase__	)

														lowerCamelCase__   :      Union[str, Any]			    =			vocab_size
														lowerCamelCase__   :      str			    =			max_position_embeddings
														lowerCamelCase__   :      Tuple			    =			hidden_size
														lowerCamelCase__   :      Dict			    =			num_hidden_layers
														lowerCamelCase__   :      Tuple			    =			num_attention_heads
														lowerCamelCase__   :      Tuple			    =			intermediate_size
														lowerCamelCase__   :      Any			    =			hidden_act
														lowerCamelCase__   :      int			    =			hidden_dropout_prob
														lowerCamelCase__   :      List[str]			    =			attention_probs_dropout_prob
														lowerCamelCase__   :      Dict			    =			initializer_range
														lowerCamelCase__   :      List[Any]			    =			type_vocab_size
														lowerCamelCase__   :      Tuple			    =			layer_norm_eps
														lowerCamelCase__   :      Optional[Any]			    =			use_cache
														lowerCamelCase__   :      Optional[Any]			    =			question_token_id

