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

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

class        __SCREAMING_SNAKE_CASE     (   _lowerCAmelCase							):
				UpperCAmelCase	=      RetriBertConfig
				UpperCAmelCase	=      None
				UpperCAmelCase	=      '''retribert'''







				def   lowercase_		(    self    :Optional[Any]      ,__UpperCAmelCase    :Union[str, Any]  )      ->					int:




									"""simple docstring"""



									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  )





UpperCAmelCase       :    Optional[int]									=			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.'''						,       _lowerCAmelCase						,       )
class        __SCREAMING_SNAKE_CASE     (   _lowerCAmelCase							):







				def __init__(    self    :List[Any]      ,__UpperCAmelCase    :RetriBertConfig  )      ->					None:




									"""simple docstring"""



									super().__init__(__UpperCAmelCase  )
									lowerCamelCase__		:   Tuple  				=					config.projection_dim

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

									lowerCamelCase__		:   Any  				=					nn.CrossEntropyLoss(reduction='''mean'''  )

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







				def   lowercase_		(    self    :Tuple      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :Dict      ,__UpperCAmelCase    :List[Any]      ,__UpperCAmelCase    :Dict=-1      ,)      ->					Union[str, Any]:




									"""simple docstring"""



									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__		:   int  				=					input_ids.device
														lowerCamelCase__		:   Optional[int]  				=					input_ids.size()
														lowerCamelCase__		:   Optional[int]  				=					torch.zeros(__UpperCAmelCase      ,dtype=torch.long      ,device=__UpperCAmelCase  )
														lowerCamelCase__		:   List[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    :Union[str, Any]  ):
																			lowerCamelCase__		:   Optional[int]  				=					sent_encoder.encoder(
																			    inputs[0]      ,attention_mask=inputs[1]      ,head_mask=__UpperCAmelCase      ,)
																			lowerCamelCase__		:   Any  				=					encoder_outputs[0]
																			lowerCamelCase__		:   int  				=					sent_encoder.pooler(__UpperCAmelCase  )
																			return pooled_output

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







				def   lowercase_		(    self    :int      ,__UpperCAmelCase    :str      ,__UpperCAmelCase    :List[Any]=None      ,__UpperCAmelCase    :Optional[int]=-1      ,)      ->					Tuple:




									"""simple docstring"""



									lowerCamelCase__		:   Tuple  				=					self.embed_sentences_checkpointed(
									    __UpperCAmelCase      ,__UpperCAmelCase      ,self.bert_query      ,__UpperCAmelCase      ,)
									return self.project_query(__UpperCAmelCase  )







				def   lowercase_		(    self    :int      ,__UpperCAmelCase    :Any      ,__UpperCAmelCase    :str=None      ,__UpperCAmelCase    :Any=-1      ,)      ->					Optional[int]:




									"""simple docstring"""



									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   lowercase_		(    self    :Optional[Any]      ,__UpperCAmelCase    :torch.LongTensor      ,__UpperCAmelCase    :Optional[torch.FloatTensor]      ,__UpperCAmelCase    :torch.LongTensor      ,__UpperCAmelCase    :Optional[torch.FloatTensor]      ,__UpperCAmelCase    :int = -1      ,)      ->					torch.FloatTensor:




									"""simple docstring"""



									lowerCamelCase__		:   Dict  				=					input_ids_query.device
									lowerCamelCase__		:   List[Any]  				=					self.embed_questions(__UpperCAmelCase      ,__UpperCAmelCase      ,__UpperCAmelCase  )
									lowerCamelCase__		:   Optional[int]  				=					self.embed_answers(__UpperCAmelCase      ,__UpperCAmelCase      ,__UpperCAmelCase  )
									lowerCamelCase__		:   int  				=					torch.mm(__UpperCAmelCase      ,a_reps.t()  )
									lowerCamelCase__		:   Any  				=					self.ce_loss(__UpperCAmelCase      ,torch.arange(compare_scores.shape[1]  ).to(__UpperCAmelCase  )  )
									lowerCamelCase__		:   Union[str, Any]  				=					self.ce_loss(compare_scores.t()      ,torch.arange(compare_scores.shape[0]  ).to(__UpperCAmelCase  )  )
									lowerCamelCase__		:   List[Any]  				=					(loss_qa + loss_aq) / 2
									return loss







"""simple docstring"""




import os
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device


if is_torch_available():
					import torch

					from transformers import GPTaLMHeadModel

@require_torch
@require_sentencepiece
@require_tokenizers
class        __SCREAMING_SNAKE_CASE     (   unittest.TestCase							):







				@slow
				@unittest.skip('''Model is not available.'''  )
				def   lowercase_		(    self    :Union[str, Any]  )      ->					Optional[int]:




									"""simple docstring"""



									lowerCamelCase__		:   Any  				=					'''nvidia/megatron-gpt2-345m/'''
									if "MYDIR" in os.environ:
														lowerCamelCase__		:   str  				=					os.path.join(os.environ['''MYDIR''']      ,__UpperCAmelCase  )
									lowerCamelCase__		:   Dict  				=					GPTaLMHeadModel.from_pretrained(__UpperCAmelCase  )
									model.to(__UpperCAmelCase  )
									model.half()

									lowerCamelCase__		:   Dict  				=					torch.tensor(
									    [[1_01, 71_10, 10_05, 10_56, 20_23, 1_13_33, 1_74_13, 10_29, 1_02]]      ,device=__UpperCAmelCase      ,dtype=torch.long      ,)

									with torch.no_grad():
														lowerCamelCase__		:   Tuple  				=					model(__UpperCAmelCase  ).logits

									lowerCamelCase__		:   List[str]  				=					torch.Size((1, 9, 5_02_57)  )
									self.assertEqual(output.shape      ,__UpperCAmelCase  )

									lowerCamelCase__		:   Tuple  				=					torch.tensor(
									    [
									        4.9_414,
									        -0.2_920,
									        -1.2_148,
									        -4.0_273,
									        -0.5_161,
									        -5.2_109,
									        -1.2_412,
									        -1.8_301,
									        -1.7_734,
									        -4.7_148,
									        -0.2_317,
									        -1.0_811,
									        -2.1_777,
									        0.4_141,
									        -3.7_969,
									        -4.0_586,
									        -2.5_332,
									        -3.3_809,
									        4.3_867,
									    ]      ,device=__UpperCAmelCase      ,dtype=torch.half      ,)

									for i in range(19  ):
														lowerCamelCase__				,						lowerCamelCase__		:   Dict  				=					8 * i // 17, 27_92 * i  # along the diagonal
														lowerCamelCase__				,						lowerCamelCase__		:   Optional[int]  				=					output[0, r, c], expected_diag[i]
														lowerCamelCase__		:   Dict  				=					F"""row={r} col={c} computed={computed} expected={expected}"""
														self.assertAlmostEqual(__UpperCAmelCase      ,__UpperCAmelCase      ,delta=1E-4      ,msg=__UpperCAmelCase  )






