

"""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__ :	int						= [
    """yjernite/retribert-base-uncased""",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]


class 			_snake_case     (						UpperCamelCase       ):
						__snake_case 			=     RetriBertConfig
						__snake_case 			=     None
						__snake_case 			=     'retribert'







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						Dict:
											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.'						,			UpperCamelCase						,			)
class 			_snake_case     (						UpperCamelCase       ):







						def __init__(self     ,							UpperCAmelCase_							)			->						None:
											super().__init__(UpperCAmelCase_							)
											__lowercase												=			config.projection_dim

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

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

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







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_=-1     ,							)			->						Tuple:
											# 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
																__lowercase												=			input_ids.device
																__lowercase												=			input_ids.size()
																__lowercase												=			torch.zeros(UpperCAmelCase_     ,							dtype=torch.long     ,							device=UpperCAmelCase_							)
																__lowercase												=			[None] * sent_encoder.config.num_hidden_layers
																__lowercase												=			sent_encoder.get_extended_attention_mask(
																    UpperCAmelCase_     ,							UpperCAmelCase_							)

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

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







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=-1     ,							)			->						Optional[int]:
											__lowercase												=			self.embed_sentences_checkpointed(
											    UpperCAmelCase_     ,							UpperCAmelCase_     ,							self.bert_query     ,							UpperCAmelCase_     ,							)
											return self.project_query(UpperCAmelCase_							)







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=-1     ,							)			->						Dict:
											__lowercase												=			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        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_ = -1     ,							)			->						torch.FloatTensor:
											__lowercase												=			input_ids_query.device
											__lowercase												=			self.embed_questions(UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)
											__lowercase												=			self.embed_answers(UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)
											__lowercase												=			torch.mm(UpperCAmelCase_     ,							a_reps.t()							)
											__lowercase												=			self.ce_loss(UpperCAmelCase_     ,							torch.arange(compare_scores.shape[1]							).to(UpperCAmelCase_							)							)
											__lowercase												=			self.ce_loss(compare_scores.t()     ,							torch.arange(compare_scores.shape[0]							).to(UpperCAmelCase_							)							)
											__lowercase												=			(loss_qa + loss_aq) / 2
											return loss





"""simple docstring"""

def 				__UpperCamelCase   (    a__: int ,	a__: int = 10_00			)				->			str:




					"""simple docstring"""



					if (not isinstance(a__ ,	a__			)) or (digit_position <= 0):
										raise ValueError('''Digit position must be a positive integer'''			)
					elif (not isinstance(a__ ,	a__			)) or (precision < 0):
										raise ValueError('''Precision must be a nonnegative integer'''			)

					# compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly
					# accurate
					__lowercase												=			(
					    4 * _subsum(a__ ,	1 ,	a__			)
					    - 2 * _subsum(a__ ,	4 ,	a__			)
					    - _subsum(a__ ,	5 ,	a__			)
					    - _subsum(a__ ,	6 ,	a__			)
					)

					# return the first hex digit of the fractional part of the result
					return hex(int((sum_result % 1) * 16			)			)[2:]





def 				__UpperCamelCase   (    a__: int ,	a__: int ,	a__: int			)				->			float:




					"""simple docstring"""



					__lowercase												=			0.0
					for sum_index in range(digit_pos_to_extract + precision			):
										__lowercase												=			8 * sum_index + denominator_addend
										if sum_index < digit_pos_to_extract:
															# if the exponential term is an integer and we mod it by the denominator
															# before dividing, only the integer part of the sum will change;
															# the fractional part will not
															__lowercase												=			pow(
															    16 ,	digit_pos_to_extract - 1 - sum_index ,	a__			)
										else:
															__lowercase												=			pow(16 ,	digit_pos_to_extract - 1 - sum_index			)
										total += exponential_term / denominator
					return total


if __name__ == "__main__":
							import doctest

							doctest.testmod()


