



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


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

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



class 		lowerCamelCase__   (    A  ):




					'''simple docstring'''



					A_         =    RetriBertConfig
					A_         =    None
					A_         =    """retribert"""




					def     __UpperCAmelCase  (	self					:						Optional[Any]  ,	UpperCamelCase_					:						List[str]       )	->							List[str]:



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






_A					:     Any      =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."""						, A						, )
class 		lowerCamelCase__   (    A  ):




					'''simple docstring'''



					def __init__(	self					:						Any  ,	UpperCamelCase_					:						RetriBertConfig       )	->							None:



						'''simple docstring'''





						super().__init__(UpperCamelCase_       )
						_lowercase       :							Dict  	=		config.projection_dim

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

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

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




					def     __UpperCAmelCase  (	self					:						Optional[int]  ,	UpperCamelCase_					:						Tuple  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Tuple  ,	UpperCamelCase_					:						str=-1  ,	)	->							Union[str, 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
							_lowercase       :							Optional[int]  	=		input_ids.device
							_lowercase       :							Optional[Any]  	=		input_ids.size()
							_lowercase       :							Any  	=		torch.zeros(UpperCamelCase_  ,	dtype=torch.long  ,	device=UpperCamelCase_       )
							_lowercase       :							Optional[Any]  	=		[None] * sent_encoder.config.num_hidden_layers
							_lowercase       :							torch.Tensor  	=		sent_encoder.get_extended_attention_mask(
							    UpperCamelCase_  ,	UpperCamelCase_       )

							# define function for checkpointing
							def partial_encode(*UpperCamelCase_					:						Union[str, Any]       ):
								_lowercase       :							int  	=		sent_encoder.encoder(
								    inputs[0]  ,	attention_mask=inputs[1]  ,	head_mask=UpperCamelCase_  ,	)
								_lowercase       :							Dict  	=		encoder_outputs[0]
								_lowercase       :							List[Any]  	=		sent_encoder.pooler(UpperCamelCase_       )
								return pooled_output

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




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



						'''simple docstring'''





						_lowercase       :							List[Any]  	=		self.embed_sentences_checkpointed(
						    UpperCamelCase_  ,	UpperCamelCase_  ,	self.bert_query  ,	UpperCamelCase_  ,	)
						return self.project_query(UpperCamelCase_       )




					def     __UpperCAmelCase  (	self					:						List[Any]  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Any=None  ,	UpperCamelCase_					:						Optional[Any]=-1  ,	)	->							Any:



						'''simple docstring'''





						_lowercase       :							int  	=		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					:						Optional[int]  ,	UpperCamelCase_					:						torch.LongTensor  ,	UpperCamelCase_					:						Optional[torch.FloatTensor]  ,	UpperCamelCase_					:						torch.LongTensor  ,	UpperCamelCase_					:						Optional[torch.FloatTensor]  ,	UpperCamelCase_					:						int = -1  ,	)	->							torch.FloatTensor:



						'''simple docstring'''





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





'''simple docstring'''

def     __UpperCamelCase					(				_lowercase = 1000       )			->      int:
	_lowercase       :							Dict  	=		0
	_lowercase       :							int  	=		0
	while 1:
		num += 3
		if num >= n:
			break
		total += num
		num += 2
		if num >= n:
			break
		total += num
		num += 1
		if num >= n:
			break
		total += num
		num += 3
		if num >= n:
			break
		total += num
		num += 1
		if num >= n:
			break
		total += num
		num += 2
		if num >= n:
			break
		total += num
		num += 3
		if num >= n:
			break
		total += num
	return total


if __name__ == "__main__":
		print(F'''{solution() = }''')
