
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


lowercase__							:							List[str]													=     logging.get_logger(__name__)

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






class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							_snake_case       						=					RetriBertConfig
							_snake_case       						=					None
							_snake_case       						=					'retribert'



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				int:





													'''simple docstring'''






													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     )





lowercase__							:							Optional[Any]													=     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.'				,						SCREAMING_SNAKE_CASE_				,						)
class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							def __init__(					self       ,		SCREAMING_SNAKE_CASE_     )->				None:





													'''simple docstring'''






													super().__init__(SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     config.projection_dim

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

													__UpperCamelCase       					=     nn.CrossEntropyLoss(reduction='''mean'''     )

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



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_=-1       ,		)->				Union[str, Any]:





													'''simple docstring'''






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

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

																			# run embedding layer on everything at once
																			__UpperCamelCase       					=     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
																			__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(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       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=-1       ,		)->				str:





													'''simple docstring'''






													__UpperCamelCase       					=     self.embed_sentences_checkpointed(
													    SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		self.bert_query       ,		SCREAMING_SNAKE_CASE_       ,		)
													return self.project_query(SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_=None       ,		SCREAMING_SNAKE_CASE_=-1       ,		)->				Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase       					=     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       A__						(					self       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_       ,		SCREAMING_SNAKE_CASE_ = -1       ,		)->				torch.FloatTensor:





													'''simple docstring'''






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






import torch

from transformers import PreTrainedModel

from .custom_configuration import CustomConfig, NoSuperInitConfig






class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							_snake_case       						=					CustomConfig



							def __init__(					self       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													super().__init__(SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     torch.nn.Linear(config.hidden_size       ,		config.hidden_size     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				List[str]:





													'''simple docstring'''






													return self.linear(SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Any:





													'''simple docstring'''






													pass






class     SCREAMING_SNAKE_CASE__      (							SCREAMING_SNAKE_CASE_      ):

							"""simple docstring"""






							_snake_case       						=					NoSuperInitConfig



							def __init__(					self       ,		SCREAMING_SNAKE_CASE_     )->				Tuple:





													'''simple docstring'''






													super().__init__(SCREAMING_SNAKE_CASE_     )
													__UpperCamelCase       					=     torch.nn.Linear(config.attribute       ,		config.attribute     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				List[str]:





													'''simple docstring'''






													return self.linear(SCREAMING_SNAKE_CASE_     )



							def       A__						(					self       ,		SCREAMING_SNAKE_CASE_     )->				Union[str, Any]:





													'''simple docstring'''






													pass




