
"""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    =		logging.get_logger(__name__)

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




class      UpperCamelCase	(       __magic_name__      ):

				"""simple docstring"""



				UpperCAmelCase_				:      int						  =				RetriBertConfig
				UpperCAmelCase_				:      int						  =				None
				UpperCAmelCase_				:      Union[str, Any]						  =				"retribert"


				def 							A					(				self		,	lowercase__			)    ->    Tuple:
									"""simple docstring"""







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






snake_case    =		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      UpperCamelCase	(       __magic_name__      ):

				"""simple docstring"""



				def __init__(				self		,	lowercase__			)    ->    None:
									"""simple docstring"""







									super().__init__(lowercase__			)
									SCREAMING_SNAKE_CASE				=	config.projection_dim

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

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

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


				def 							A					(				self		,	lowercase__		,	lowercase__		,	lowercase__		,	lowercase__=-1		,	)    ->    Dict:
									"""simple docstring"""







									if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
														return sent_encoder(lowercase__		,	attention_mask=lowercase__			)[1]
									else:
														# prepare implicit variables
														SCREAMING_SNAKE_CASE				=	input_ids.device
														SCREAMING_SNAKE_CASE				=	input_ids.size()
														SCREAMING_SNAKE_CASE				=	torch.zeros(lowercase__		,	dtype=torch.long		,	device=lowercase__			)
														SCREAMING_SNAKE_CASE				=	[None] * sent_encoder.config.num_hidden_layers
														SCREAMING_SNAKE_CASE				=	sent_encoder.get_extended_attention_mask(
														    lowercase__		,	lowercase__			)

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

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


				def 							A					(				self		,	lowercase__		,	lowercase__=None		,	lowercase__=-1		,	)    ->    str:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	self.embed_sentences_checkpointed(
									    lowercase__		,	lowercase__		,	self.bert_query		,	lowercase__		,	)
									return self.project_query(lowercase__			)


				def 							A					(				self		,	lowercase__		,	lowercase__=None		,	lowercase__=-1		,	)    ->    Tuple:
									"""simple docstring"""







									SCREAMING_SNAKE_CASE				=	self.embed_sentences_checkpointed(
									    lowercase__		,	lowercase__		,	self.bert_query if self.bert_doc is None else self.bert_doc		,	lowercase__		,	)
									return self.project_doc(lowercase__			)




				def 							A					(				self		,	lowercase__		,	lowercase__		,	lowercase__		,	lowercase__		,	lowercase__ = -1		,	)    ->    torch.FloatTensor:
									"""simple docstring"""







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


"""simple docstring"""




from functools import lru_cache

@lru_cache
def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_			):
					if not isinstance(SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			):
										raise TypeError('k must be an integer.'			)
					if k < 0:
										raise ValueError('k integer must be greater or equal to zero.'			)
					if k == 0:
										return 0
					elif k == 1:
										return 1
					else:
										return fibonacci(k - 1			) + fibonacci(k - 2			)

def   UpperCamelCase_  (		SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			):
					SCREAMING_SNAKE_CASE				=	len(SCREAMING_SNAKE_CASE_			)
					# Find m such that F_m >= n where F_i is the i_th fibonacci number.
					SCREAMING_SNAKE_CASE				=	0
					while True:
										if fibonacci(SCREAMING_SNAKE_CASE_			) >= len_list:
															SCREAMING_SNAKE_CASE				=	i
															break
										i += 1
					SCREAMING_SNAKE_CASE				=	0
					while fibb_k > 0:
										SCREAMING_SNAKE_CASE				=	min(
										    offset + fibonacci(fibb_k - 1			),     len_list - 1			)  # Prevent out of range
										SCREAMING_SNAKE_CASE				=	arr[index_k]
										if item_k_1 == val:
															return index_k
										elif val < item_k_1:
															fibb_k -= 1
										elif val > item_k_1:
															offset += fibonacci(fibb_k - 1			)
															fibb_k -= 2
					else:
										return -1


if __name__ == "__main__":
	import doctest

	doctest.testmod()
