

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


_lowerCamelCase							=logging.get_logger(__name__)

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



class 						a_			(				lowerCamelCase_	):



      """simple docstring"""







      __UpperCAmelCase     						= RetriBertConfig
      __UpperCAmelCase     						= None
      __UpperCAmelCase     						= 'retribert'
      def 			_lowerCAmelCase	( self	:				Optional[Any]     ,snake_case	:				List[str]							):





           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							)







_lowerCamelCase							=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.'					,     lowerCamelCase_					,     )
class 						a_			(				lowerCamelCase_	):



      """simple docstring"""







      def __init__( self	:				Any     ,snake_case	:				RetriBertConfig							):
           super().__init__(UpperCamelCase_							)
           SCREAMING_SNAKE_CASE 		=config.projection_dim

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

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

           # Initialize weights and apply final processing
           self.post_init()
      def 			_lowerCAmelCase	( self	:				Optional[int]     ,snake_case	:				Tuple     ,snake_case	:				Optional[Any]     ,snake_case	:				Tuple     ,snake_case	:				str=-1     ,):





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

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

                # run embedding layer on everything at once
                SCREAMING_SNAKE_CASE 		=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
                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(UpperCamelCase_     ,UpperCamelCase_     ,UpperCamelCase_							)
                     pooled_output_list.append(UpperCamelCase_							)
                return torch.cat(UpperCamelCase_     ,dim=0							)
      def 			_lowerCAmelCase	( self	:				List[Any]     ,snake_case	:				List[str]     ,snake_case	:				List[str]=None     ,snake_case	:				List[str]=-1     ,):
           SCREAMING_SNAKE_CASE 		=self.embed_sentences_checkpointed(
               UpperCamelCase_     ,UpperCamelCase_     ,self.bert_query     ,UpperCamelCase_     ,)
           return self.project_query(UpperCamelCase_							)
      def 			_lowerCAmelCase	( self	:				List[Any]     ,snake_case	:				Optional[Any]     ,snake_case	:				Any=None     ,snake_case	:				Optional[Any]=-1     ,):
           SCREAMING_SNAKE_CASE 		=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 			_lowerCAmelCase	( self	:				Optional[int]     ,snake_case	:				torch.LongTensor     ,snake_case	:				Optional[torch.FloatTensor]     ,snake_case	:				torch.LongTensor     ,snake_case	:				Optional[torch.FloatTensor]     ,snake_case	:				int = -1     ,):
           SCREAMING_SNAKE_CASE 		=input_ids_query.device
           SCREAMING_SNAKE_CASE 		=self.embed_questions(UpperCamelCase_     ,UpperCamelCase_     ,UpperCamelCase_							)
           SCREAMING_SNAKE_CASE 		=self.embed_answers(UpperCamelCase_     ,UpperCamelCase_     ,UpperCamelCase_							)
           SCREAMING_SNAKE_CASE 		=torch.mm(UpperCamelCase_     ,a_reps.t()							)
           SCREAMING_SNAKE_CASE 		=self.ce_loss(UpperCamelCase_     ,torch.arange(compare_scores.shape[1]							).to(UpperCamelCase_							)							)
           SCREAMING_SNAKE_CASE 		=self.ce_loss(compare_scores.t()     ,torch.arange(compare_scores.shape[0]							).to(UpperCamelCase_							)							)
           SCREAMING_SNAKE_CASE 		=(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() = }''')
