






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

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

class _lowercase      (							_lowercase						):
							a							 =			RetriBertConfig
							a							 =			None
							a							 =			"""retribert"""




							def 						lowerCamelCase_							(				self:							Optional[int]     ,				UpperCamelCase__:							Union[str, Any]	):
														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      :     Tuple       	=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."""							, _lowercase							, )
class _lowercase      (							_lowercase						):




							def __init__(				self:							Any     ,				UpperCamelCase__:							RetriBertConfig	):
														super().__init__(UpperCamelCase__	)
														lowerCamelCase__   :      Any			    =			config.projection_dim

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

														lowerCamelCase__   :      Tuple			    =			nn.CrossEntropyLoss(reduction="""mean"""	)

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




							def 						lowerCamelCase_							(				self:							Any     ,				UpperCamelCase__:							Optional[Any]     ,				UpperCamelCase__:							Optional[Any]     ,				UpperCamelCase__:							List[str]     ,				UpperCamelCase__:							Optional[int]=-1     ,				):
														# reproduces BERT forward pass with checkpointing
														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
																					lowerCamelCase__   :      Tuple			    =			input_ids.device
																					lowerCamelCase__   :      Optional[int]			    =			input_ids.size()
																					lowerCamelCase__   :      List[str]			    =			torch.zeros(UpperCamelCase__     ,				dtype=torch.long     ,				device=UpperCamelCase__	)
																					lowerCamelCase__   :      str			    =			[None] * sent_encoder.config.num_hidden_layers
																					lowerCamelCase__   :      torch.Tensor			    =			sent_encoder.get_extended_attention_mask(
																					    UpperCamelCase__     ,				UpperCamelCase__	)

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

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




							def 						lowerCamelCase_							(				self:							Tuple     ,				UpperCamelCase__:							Any     ,				UpperCamelCase__:							Optional[int]=None     ,				UpperCamelCase__:							Optional[int]=-1     ,				):
														lowerCamelCase__   :      List[str]			    =			self.embed_sentences_checkpointed(
														    UpperCamelCase__     ,				UpperCamelCase__     ,				self.bert_query     ,				UpperCamelCase__     ,				)
														return self.project_query(UpperCamelCase__	)




							def 						lowerCamelCase_							(				self:							Optional[Any]     ,				UpperCamelCase__:							List[str]     ,				UpperCamelCase__:							Tuple=None     ,				UpperCamelCase__:							str=-1     ,				):
														lowerCamelCase__   :      Optional[Any]			    =			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:							List[Any]     ,				UpperCamelCase__:							torch.LongTensor     ,				UpperCamelCase__:							Optional[torch.FloatTensor]     ,				UpperCamelCase__:							torch.LongTensor     ,				UpperCamelCase__:							Optional[torch.FloatTensor]     ,				UpperCamelCase__:							int = -1     ,				):
														lowerCamelCase__   :      Tuple			    =			input_ids_query.device
														lowerCamelCase__   :      Union[str, Any]			    =			self.embed_questions(UpperCamelCase__     ,				UpperCamelCase__     ,				UpperCamelCase__	)
														lowerCamelCase__   :      Dict			    =			self.embed_answers(UpperCamelCase__     ,				UpperCamelCase__     ,				UpperCamelCase__	)
														lowerCamelCase__   :      List[str]			    =			torch.mm(UpperCamelCase__     ,				a_reps.t()	)
														lowerCamelCase__   :      Tuple			    =			self.ce_loss(UpperCamelCase__     ,				torch.arange(compare_scores.shape[1]	).to(UpperCamelCase__	)	)
														lowerCamelCase__   :      Optional[Any]			    =			self.ce_loss(compare_scores.t()     ,				torch.arange(compare_scores.shape[0]	).to(UpperCamelCase__	)	)
														lowerCamelCase__   :      Any			    =			(loss_qa + loss_aq) / 2
														return loss









'''simple docstring'''







def 					SCREAMING_SNAKE_CASE_			(UpperCamelCase							,     UpperCamelCase = 13 ) ->			str:
							lowerCamelCase__   :      Dict			    =			""""""
							for c in s:
														if "A" <= c <= "Z":
																					out += chr(ord("""A""" ) + (ord(UpperCamelCase ) - ord("""A""" ) + n) % 26 )
														elif "a" <= c <= "z":
																					out += chr(ord("""a""" ) + (ord(UpperCamelCase ) - ord("""a""" ) + n) % 26 )
														else:
																					out += c
							return out





def 					SCREAMING_SNAKE_CASE_			() ->			None:
							lowerCamelCase__   :      Dict			    =			input("""Enter message: """ )

							lowerCamelCase__   :      str			    =			dencrypt(UpperCamelCase							,     13 )
							print("""Encryption:"""							,     UpperCamelCase )

							lowerCamelCase__   :      List[str]			    =			dencrypt(UpperCamelCase							,     13 )
							print("""Decryption: """							,     UpperCamelCase )


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			main()

