
from dataclasses import dataclass
from typing import Callable, Optional

import datasets






@dataclass
class 					__lowercase		(					datasets.BuilderConfig       ):
					__magic_name__						:							Optional[Callable]     	=	None
					__magic_name__						:							Optional[dict]     	=	None
					__magic_name__						:							Optional[datasets.Features]     	=	None


					def        lowerCAmelCase_    (	self						)		->							Any:





									'''simple docstring'''
									assert self.generator is not None, "generator must be specified"

									if self.gen_kwargs is None:
													A_       	=  {}






class 					__lowercase		(					datasets.GeneratorBasedBuilder       ):
					__magic_name__						:							Tuple     	=	GeneratorConfig


					def        lowerCAmelCase_    (	self						)		->							int:





									'''simple docstring'''
									return datasets.DatasetInfo(features=self.config.features						)


					def        lowerCAmelCase_    (	self       ,       a__						)		->							List[str]:





									'''simple docstring'''
									return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,       gen_kwargs=self.config.gen_kwargs						)]


					def        lowerCAmelCase_    (	self       ,       **a__						)		->							Optional[int]:





									'''simple docstring'''
									for idx, ex in enumerate(self.config.generator(**a__						)						):
													yield idx, ex

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

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






class 					__lowercase		(					A       ):
					__magic_name__						:							Any     	=	RetriBertConfig
					__magic_name__						:							Optional[Any]     	=	None
					__magic_name__						:							str     	=	'''retribert'''


					def        lowerCAmelCase_    (	self       ,       a__						)		->							int:





									'''simple docstring'''
									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   :		Optional[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 					__lowercase		(					A       ):


					def __init__(	self       ,       a__						)		->							None:





									'''simple docstring'''
									super().__init__(a__						)
									A_       	=  config.projection_dim

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

									A_       	=  nn.CrossEntropyLoss(reduction='''mean'''						)

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


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__=-1       ,       )		->							int:





									'''simple docstring'''
									# 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
													A_       	=  input_ids.device
													A_       	=  input_ids.size()
													A_       	=  torch.zeros(a__       ,       dtype=torch.long       ,       device=a__						)
													A_       	=  [None] * sent_encoder.config.num_hidden_layers
													A_       	=  sent_encoder.get_extended_attention_mask(
													    a__       ,       a__						)

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

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


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__=None       ,       a__=-1       ,       )		->							int:





									'''simple docstring'''
									A_       	=  self.embed_sentences_checkpointed(
									    a__       ,       a__       ,       self.bert_query       ,       a__       ,       )
									return self.project_query(a__						)


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__=None       ,       a__=-1       ,       )		->							Optional[Any]:





									'''simple docstring'''
									A_       	=  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        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__ = -1       ,       )		->							torch.FloatTensor:





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