


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


lowerCAmelCase			:   List[str] 		=  logging.get_logger(__name__)

lowerCAmelCase			:   Dict 		=  [
    'yjernite/retribert-base-uncased',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]
class 		UpperCamelCase__    (       _a		):



     """simple docstring"""






     __magic_name__				=			RetriBertConfig
     __magic_name__				=			None
     __magic_name__				=			"retribert"







     def a		(       self					,		snake_case__      ):

            '''simple docstring'''

            if isinstance(lowerCAmelCase_					,		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(lowerCAmelCase_					,		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(lowerCAmelCase_					,		nn.LayerNorm      ):
                   module.bias.data.zero_()
                   module.weight.data.fill_(1.0      )
lowerCAmelCase			:   List[Any] 		=  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."			,    _a			,    )
class 		UpperCamelCase__    (       _a		):



     """simple docstring"""






     def __init__(       self					,		snake_case__      ):

            '''simple docstring'''

            super().__init__(lowerCAmelCase_      )
            _lowerCAmelCase			:							List[str]      	=				config.projection_dim

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

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

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







     def a		(       self					,		snake_case__					,		snake_case__					,		snake_case__					,		snake_case__=-1					,		):

            '''simple docstring'''

            if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
                   return sent_encoder(lowerCAmelCase_					,		attention_mask=lowerCAmelCase_      )[1]
            else:
                   # prepare implicit variables
                   _lowerCAmelCase			:							Tuple      	=				input_ids.device
                   _lowerCAmelCase			:							Tuple      	=				input_ids.size()
                   _lowerCAmelCase			:							Optional[int]      	=				torch.zeros(lowerCAmelCase_					,		dtype=torch.long					,		device=lowerCAmelCase_      )
                   _lowerCAmelCase			:							int      	=				[None] * sent_encoder.config.num_hidden_layers
                   _lowerCAmelCase			:							List[str]      	=				sent_encoder.get_extended_attention_mask(
                       lowerCAmelCase_					,		lowerCAmelCase_      )

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

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







     def a		(       self					,		snake_case__					,		snake_case__=None					,		snake_case__=-1					,		):

            '''simple docstring'''

            _lowerCAmelCase			:							int      	=				self.embed_sentences_checkpointed(
                lowerCAmelCase_					,		lowerCAmelCase_					,		self.bert_query					,		lowerCAmelCase_					,		)
            return self.project_query(lowerCAmelCase_      )







     def a		(       self					,		snake_case__					,		snake_case__=None					,		snake_case__=-1					,		):

            '''simple docstring'''

            _lowerCAmelCase			:							int      	=				self.embed_sentences_checkpointed(
                lowerCAmelCase_					,		lowerCAmelCase_					,		self.bert_query if self.bert_doc is None else self.bert_doc					,		lowerCAmelCase_					,		)
            return self.project_doc(lowerCAmelCase_      )







     def a		(       self					,		snake_case__					,		snake_case__					,		snake_case__					,		snake_case__					,		snake_case__ = -1					,		):

            '''simple docstring'''

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







'''simple docstring'''


from __future__ import annotations
def 		snake_case_    (UpperCamelCase       :  int      ):





							'''simple docstring'''


							_a	     =				[0] * max_one

							for i in range(0 ,						UpperCamelCase      ):
														_a	     =				i

							for i in range(2 ,						UpperCamelCase      ):
														if totients[i] == i:
																					for j in range(UpperCamelCase ,						UpperCamelCase ,						UpperCamelCase      ):
																												totients[j] -= totients[j] // i

							return totients
def 		snake_case_    (UpperCamelCase       :  int ,						UpperCamelCase       :  int      ):





							'''simple docstring'''


							return sorted(str(UpperCamelCase      )      ) == sorted(str(UpperCamelCase      )      )
def 		snake_case_    (UpperCamelCase       :  int = 1000_0000      ):





							'''simple docstring'''


							_a	     =				1  # i
							_a	     =				0  # φ(i)
							_a	     =				get_totients(max_n + 1      )

							for i in range(2 ,						max_n + 1      ):
														_a	     =				totients[i]

														if i * min_denominator < min_numerator * t and has_same_digits(UpperCamelCase ,						UpperCamelCase      ):
																					_a	     =				i
																					_a	     =				t

							return min_numerator


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

