



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

UpperCAmelCase :				Optional[Any]							=[
    """yjernite/retribert-base-uncased""",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]


class    _lowercase (a_   ):
				'''simple docstring'''







				lowercase__     =    RetriBertConfig
				lowercase__     =    None
				lowercase__     =    """retribert"""

				def    _lowerCamelCase       (			self  ,			snake_case__     ):

									'''simple docstring'''


									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 :				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."""   , a_   , )
class    _lowercase (a_   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__     ):

									'''simple docstring'''


									super().__init__(snake_case__     )
									UpperCamelCase_			= config.projection_dim

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

									UpperCamelCase_			= nn.CrossEntropyLoss(reduction="mean"     )

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

				def    _lowerCamelCase       (			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(snake_case__  ,			attention_mask=snake_case__     )[1]
									else:
														# prepare implicit variables
														UpperCamelCase_			= input_ids.device
														UpperCamelCase_			= input_ids.size()
														UpperCamelCase_			= torch.zeros(snake_case__  ,			dtype=torch.long  ,			device=snake_case__     )
														UpperCamelCase_			= [None] * sent_encoder.config.num_hidden_layers
														UpperCamelCase_			= sent_encoder.get_extended_attention_mask(
														    snake_case__  ,			snake_case__     )

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

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

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

									'''simple docstring'''


									UpperCamelCase_			= self.embed_sentences_checkpointed(
									    snake_case__  ,			snake_case__  ,			self.bert_query  ,			snake_case__  ,			)
									return self.project_query(snake_case__     )

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

									'''simple docstring'''


									UpperCamelCase_			= 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    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__ = -1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= input_ids_query.device
									UpperCamelCase_			= self.embed_questions(snake_case__  ,			snake_case__  ,			snake_case__     )
									UpperCamelCase_			= self.embed_answers(snake_case__  ,			snake_case__  ,			snake_case__     )
									UpperCamelCase_			= torch.mm(snake_case__  ,			a_reps.t()     )
									UpperCamelCase_			= self.ce_loss(snake_case__  ,			torch.arange(compare_scores.shape[1]     ).to(snake_case__     )     )
									UpperCamelCase_			= self.ce_loss(compare_scores.t()  ,			torch.arange(compare_scores.shape[0]     ).to(snake_case__     )     )
									UpperCamelCase_			= (loss_qa + loss_aq) / 2
									return loss




def 				UpperCamelCase_	(					__snake_case      :    set						,      __snake_case      :    set  )->   set:




						'''simple docstring'''
						assert isinstance(__snake_case						,      __snake_case  ), F'''The input value of [set_a={set_a}] is not a set'''
						assert isinstance(__snake_case						,      __snake_case  ), F'''The input value of [set_b={set_b}] is not a set'''

						return {a + b for a in set_a for b in set_b}


if __name__ == "__main__":
					from doctest import testmod

					testmod()

