


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


UpperCAmelCase_	:     List[Any]							     =	logging.get_logger(__name__)

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





class 					lowercase__						(		_snake_case      ):





							'''simple docstring'''


							A_							:   Optional[int]   			=						RetriBertConfig
							A_							:   Any   			=						None
							A_							:   Dict   			=						"""retribert"""






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



UpperCAmelCase_	:     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."""  ,  _snake_case  ,  )
class 					lowercase__						(		_snake_case      ):





							'''simple docstring'''


							def __init__(					self					,      __snake_case						):
											super().__init__(__snake_case						)
											_SCREAMING_SNAKE_CASE				: Optional[int]  	=   config.projection_dim

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

											_SCREAMING_SNAKE_CASE				: int  	=   nn.CrossEntropyLoss(reduction="""mean"""						)

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






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case					,      __snake_case					,      __snake_case=-1					,      ):
											# reproduces BERT forward pass with checkpointing
											if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
															return sent_encoder(__snake_case					,      attention_mask=__snake_case						)[1]
											else:
															# prepare implicit variables
															_SCREAMING_SNAKE_CASE				: List[Any]  	=   input_ids.device
															_SCREAMING_SNAKE_CASE				: Any  	=   input_ids.size()
															_SCREAMING_SNAKE_CASE				: str  	=   torch.zeros(__snake_case					,      dtype=torch.long					,      device=__snake_case						)
															_SCREAMING_SNAKE_CASE				: Any  	=   [None] * sent_encoder.config.num_hidden_layers
															_SCREAMING_SNAKE_CASE				: torch.Tensor  	=   sent_encoder.get_extended_attention_mask(
															    __snake_case					,      __snake_case						)

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

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






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case=None					,      __snake_case=-1					,      ):
											_SCREAMING_SNAKE_CASE				: Dict  	=   self.embed_sentences_checkpointed(
											    __snake_case					,      __snake_case					,      self.bert_query					,      __snake_case					,      )
											return self.project_query(__snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case=None					,      __snake_case=-1					,      ):
											_SCREAMING_SNAKE_CASE				: Dict  	=   self.embed_sentences_checkpointed(
											    __snake_case					,      __snake_case					,      self.bert_query if self.bert_doc is None else self.bert_doc					,      __snake_case					,      )
											return self.project_doc(__snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case					,      __snake_case					,      __snake_case					,      __snake_case = -1					,      ):
											_SCREAMING_SNAKE_CASE				: Any  	=   input_ids_query.device
											_SCREAMING_SNAKE_CASE				: str  	=   self.embed_questions(__snake_case					,      __snake_case					,      __snake_case						)
											_SCREAMING_SNAKE_CASE				: str  	=   self.embed_answers(__snake_case					,      __snake_case					,      __snake_case						)
											_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   torch.mm(__snake_case					,      a_reps.t()						)
											_SCREAMING_SNAKE_CASE				: List[str]  	=   self.ce_loss(__snake_case					,      torch.arange(compare_scores.shape[1]						).to(__snake_case						)						)
											_SCREAMING_SNAKE_CASE				: Tuple  	=   self.ce_loss(compare_scores.t()					,      torch.arange(compare_scores.shape[0]						).to(__snake_case						)						)
											_SCREAMING_SNAKE_CASE				: List[str]  	=   (loss_qa + loss_aq) / 2
											return loss








'''simple docstring'''


def     snake_case_     (						SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





				return (input_a, input_a).count(0  ) % 2







def     snake_case_     (						):







				"""simple docstring"""





				assert xor_gate(0							,   0  ) == 0
				assert xor_gate(0							,   1  ) == 1
				assert xor_gate(1							,   0  ) == 1
				assert xor_gate(1							,   1  ) == 0


if __name__ == "__main__":
				print(xor_gate(0, 0))
				print(xor_gate(0, 1))




