

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

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


class      lowerCamelCase_ (			_snake_case):
 _lowerCAmelCase									=	RetriBertConfig
 _lowerCAmelCase									=	None
 _lowerCAmelCase									=	"""retribert"""




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



_SCREAMING_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.'''	,				_snake_case	,				)
class      lowerCamelCase_ (			_snake_case):




 def __init__(			self  ,  _UpperCAmelCase							):
   super().__init__(A_							)
   __UpperCAmelCase	:  List[Any]		=     config.projection_dim

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

   __UpperCAmelCase	:  Dict		=     nn.CrossEntropyLoss(reduction='mean'							)

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




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

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

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




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase=None  ,  _UpperCAmelCase=-1  ,  ):
   __UpperCAmelCase	:  Optional[Any]		=     self.embed_sentences_checkpointed(
       A_  ,  A_  ,  self.bert_query  ,  A_  ,  )
   return self.project_query(A_							)




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase=None  ,  _UpperCAmelCase=-1  ,  ):
   __UpperCAmelCase	:  List[str]		=     self.embed_sentences_checkpointed(
       A_  ,  A_  ,  self.bert_query if self.bert_doc is None else self.bert_doc  ,  A_  ,  )
   return self.project_doc(A_							)




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








A__										=      10**8





def 				__a							(       __A						):
    if n % 10 == 0:
        return False
    SCREAMING_SNAKE_CASE__         =    str(__A						)
    return s == s[::-1]





def 				__a							(       ):
    SCREAMING_SNAKE_CASE__         =    set()
    SCREAMING_SNAKE_CASE__         =    1
    SCREAMING_SNAKE_CASE__         =    5
    while sum_squares < LIMIT:
        SCREAMING_SNAKE_CASE__         =    first_square + 1
        while sum_squares < LIMIT:
            if is_palindrome(__A						):
                answer.add(__A						)
            last_square += 1
            sum_squares += last_square**2
        first_square += 1
        SCREAMING_SNAKE_CASE__         =    first_square**2 + (first_square + 1) ** 2

    return sum(__A						)


if __name__ == "__main__":
  print(solution())


