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


UpperCAmelCase            = logging.get_logger(__name__)

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

class     a (					__magic_name__     ):
				_snake_case		     =			RetriBertConfig
				_snake_case		     =			None
				_snake_case		     =			'''retribert'''




				def 						__snake_case				(				self						:					str,     SCREAMING_SNAKE_CASE_						:					List[Any]   ):
										if isinstance(SCREAMING_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(SCREAMING_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(SCREAMING_SNAKE_CASE_,     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.'''					,__magic_name__					,)
class     a (					__magic_name__     ):




				def __init__(				self						:					Dict,     SCREAMING_SNAKE_CASE_						:					RetriBertConfig   ):
										super().__init__(SCREAMING_SNAKE_CASE_   )
										snake_case							:  int			=     config.projection_dim

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

										snake_case							:  Tuple			=     nn.CrossEntropyLoss(reduction='''mean'''   )

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




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

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

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




				def 						__snake_case				(				self						:					List[str],     SCREAMING_SNAKE_CASE_						:					Union[str, Any],     SCREAMING_SNAKE_CASE_						:					Union[str, Any]=None,     SCREAMING_SNAKE_CASE_						:					List[Any]=-1,     ):
										snake_case							:  Optional[Any]			=     self.embed_sentences_checkpointed(
										    SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     self.bert_query,     SCREAMING_SNAKE_CASE_,     )
										return self.project_query(SCREAMING_SNAKE_CASE_   )




				def 						__snake_case				(				self						:					Union[str, Any],     SCREAMING_SNAKE_CASE_						:					Optional[Any],     SCREAMING_SNAKE_CASE_						:					List[str]=None,     SCREAMING_SNAKE_CASE_						:					int=-1,     ):
										snake_case							:  int			=     self.embed_sentences_checkpointed(
										    SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     self.bert_query if self.bert_doc is None else self.bert_doc,     SCREAMING_SNAKE_CASE_,     )
										return self.project_doc(SCREAMING_SNAKE_CASE_   )




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





'''simple docstring'''



def       _a      (		_lowercase   :      str    ):





     '''simple docstring'''






     __UpperCAmelCase      :					Union[str, Any]    				=     5381
     for x in s:
          __UpperCAmelCase      :					Union[str, Any]    				=     ((hash_value << 5) + hash_value) + ord(_lowercase    )
     return hash_value & 0XFFFFFFFF