






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        snake_case_					(						__UpperCamelCase			):

						"""simple docstring"""



						snake_case__   					=			RetriBertConfig
						snake_case__   					=			None
						snake_case__   					=			"""retribert"""



						def 					UpperCAmelCase__				(self:				List[str]   ,				__UpperCAmelCase:				int      )						->    List[Any]:




											'''simple docstring'''



											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      )


UpperCAmelCase__			 =	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."""		,       __UpperCamelCase		,       )
class        snake_case_					(						__UpperCamelCase			):

						"""simple docstring"""



						def __init__(self:				int   ,				__UpperCAmelCase:				RetriBertConfig      )						->    None:




											'''simple docstring'''



											super().__init__(__UpperCAmelCase      )
											__a				:	int			=				config.projection_dim

											__a				:	List[str]			=				BertModel(__UpperCAmelCase      )
											__a				:	Union[str, Any]			=				None if config.share_encoders else BertModel(__UpperCAmelCase      )
											__a				:	Union[str, Any]			=				nn.Dropout(config.hidden_dropout_prob      )
											__a				:	List[Any]			=				nn.Linear(config.hidden_size   ,				config.projection_dim   ,				bias=__UpperCAmelCase      )
											__a				:	Tuple			=				nn.Linear(config.hidden_size   ,				config.projection_dim   ,				bias=__UpperCAmelCase      )

											__a				:	Tuple			=				nn.CrossEntropyLoss(reduction="mean"      )

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



						def 					UpperCAmelCase__				(self:				Optional[int]   ,				__UpperCAmelCase:				Union[str, Any]   ,				__UpperCAmelCase:				Tuple   ,				__UpperCAmelCase:				Optional[int]   ,				__UpperCAmelCase:				List[str]=-1   ,				)						->    List[Any]:




											'''simple docstring'''



											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				:	Any			=				input_ids.device
																__a				:	int			=				input_ids.size()
																__a				:	List[Any]			=				torch.zeros(__UpperCAmelCase   ,				dtype=torch.long   ,				device=__UpperCAmelCase      )
																__a				:	List[str]			=				[None] * sent_encoder.config.num_hidden_layers
																__a				:	torch.Tensor			=				sent_encoder.get_extended_attention_mask(
																    __UpperCAmelCase   ,				__UpperCAmelCase      )

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

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



						def 					UpperCAmelCase__				(self:				List[str]   ,				__UpperCAmelCase:				Union[str, Any]   ,				__UpperCAmelCase:				Union[str, Any]=None   ,				__UpperCAmelCase:				int=-1   ,				)						->    int:




											'''simple docstring'''



											__a				:	Optional[Any]			=				self.embed_sentences_checkpointed(
											    __UpperCAmelCase   ,				__UpperCAmelCase   ,				self.bert_query   ,				__UpperCAmelCase   ,				)
											return self.project_query(__UpperCAmelCase      )



						def 					UpperCAmelCase__				(self:				Dict   ,				__UpperCAmelCase:				Tuple   ,				__UpperCAmelCase:				List[Any]=None   ,				__UpperCAmelCase:				str=-1   ,				)						->    Union[str, Any]:




											'''simple docstring'''



											__a				:	Tuple			=				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 					UpperCAmelCase__				(self:				Tuple   ,				__UpperCAmelCase:				torch.LongTensor   ,				__UpperCAmelCase:				Optional[torch.FloatTensor]   ,				__UpperCAmelCase:				torch.LongTensor   ,				__UpperCAmelCase:				Optional[torch.FloatTensor]   ,				__UpperCAmelCase:				int = -1   ,				)						->    torch.FloatTensor:




											'''simple docstring'''



											__a				:	List[Any]			=				input_ids_query.device
											__a				:	Union[str, Any]			=				self.embed_questions(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )
											__a				:	Union[str, Any]			=				self.embed_answers(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )
											__a				:	Dict			=				torch.mm(__UpperCAmelCase   ,				a_reps.t()      )
											__a				:	Any			=				self.ce_loss(__UpperCAmelCase   ,				torch.arange(compare_scores.shape[1]      ).to(__UpperCAmelCase      )      )
											__a				:	List[str]			=				self.ce_loss(compare_scores.t()   ,				torch.arange(compare_scores.shape[0]      ).to(__UpperCAmelCase      )      )
											__a				:	str			=				(loss_qa + loss_aq) / 2
											return loss













def 						a_      (__A			)							->	list:



					"""simple docstring"""
					if len(__A			) <= 1:
										return data
					else:
										return [
										    *quick_sort([e for e in data[1:] if e <= data[0]]			),
										    data[0],
										    *quick_sort([e for e in data[1:] if e > data[0]]			),
										]


if __name__ == "__main__":
			import doctest

			doctest.testmod()





