
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


__SCREAMING_SNAKE_CASE			:   Optional[int]         =     logging.get_logger(__name__)

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


class 		__magic_name__   (						snake_case    ):
		_lowerCAmelCase		=	RetriBertConfig
		_lowerCAmelCase		=	None
		_lowerCAmelCase		=	"retribert"





		def       _A							(							self    :	Tuple						,  lowerCamelCase__    :	Tuple				):
							if isinstance(lowerCamelCase__						,  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(lowerCamelCase__						,  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(lowerCamelCase__						,  nn.LayerNorm				):
												module.bias.data.zero_()
												module.weight.data.fill_(1.0				)



__SCREAMING_SNAKE_CASE			:   str         =     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.",				snake_case,				)
class 		__magic_name__   (						snake_case    ):





		def __init__(							self    :	List[Any]						,  lowerCamelCase__    :	RetriBertConfig				):
							super().__init__(lowerCamelCase__				)
							lowerCAmelCase		:					Dict  	=     config.projection_dim

							lowerCAmelCase		:					Tuple  	=     BertModel(lowerCamelCase__				)
							lowerCAmelCase		:					Optional[Any]  	=     None if config.share_encoders else BertModel(lowerCamelCase__				)
							lowerCAmelCase		:					Dict  	=     nn.Dropout(config.hidden_dropout_prob				)
							lowerCAmelCase		:					List[str]  	=     nn.Linear(config.hidden_size						,  config.projection_dim						,  bias=lowerCamelCase__				)
							lowerCAmelCase		:					Optional[int]  	=     nn.Linear(config.hidden_size						,  config.projection_dim						,  bias=lowerCamelCase__				)

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

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





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

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

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





		def       _A							(							self    :	Optional[Any]						,  lowerCamelCase__    :	List[str]						,  lowerCamelCase__    :	int=None						,  lowerCamelCase__    :	int=-1						,  ):
							lowerCAmelCase		:					int  	=     self.embed_sentences_checkpointed(
							    lowerCamelCase__						,  lowerCamelCase__						,  self.bert_query						,  lowerCamelCase__						,  )
							return self.project_query(lowerCamelCase__				)





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





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


from ..utils import requires_backends


__SCREAMING_SNAKE_CASE			:   Union[str, Any]         =     None


class 		__magic_name__   :





		def __init__(							self    :	Optional[int]						,  *lowerCamelCase__    :	List[str]						,  **lowerCamelCase__    :	Optional[Any]				):
							requires_backends(self						,  ['''detectron2''']				)





		@classmethod
		def       _A							(							cls    :	Dict						,  *lowerCamelCase__    :	List[str]						,  **lowerCamelCase__    :	Optional[Any]				):
							requires_backends(cls						,  ['''detectron2''']				)
