






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

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

class _lowercase      (							_UpperCAmelCase						):
							a							 =			RetriBertConfig
							a							 =			None
							a							 =			"retribert"




							def 						lowerCamelCase_							(				self:							Optional[int]     ,				UpperCamelCase__:							List[Any]	):
														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      :     List[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."""							, _UpperCAmelCase							, )
class _lowercase      (							_UpperCAmelCase						):




							def __init__(				self:							int     ,				UpperCamelCase__:							Optional[Any]	):
														super().__init__(__UpperCAmelCase	)
														lowerCamelCase__   :      Dict			    =			config.projection_dim

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

														lowerCamelCase__   :      List[str]			    =			nn.CrossEntropyLoss(reduction="""mean"""	)

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




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

																					# run embedding layer on everything at once
																					lowerCamelCase__   :      Tuple			    =			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__   :      List[Any]			    =			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__   :      str			    =			checkpoint.checkpoint(__UpperCAmelCase     ,				__UpperCAmelCase     ,				__UpperCAmelCase	)
																												pooled_output_list.append(__UpperCAmelCase	)
																					return torch.cat(__UpperCAmelCase     ,				dim=0	)




							def 						lowerCamelCase_							(				self:							str     ,				UpperCamelCase__:							Optional[Any]     ,				UpperCamelCase__:							Tuple=None     ,				UpperCamelCase__:							Optional[Any]=-1     ,				):
														lowerCamelCase__   :      Optional[int]			    =			self.embed_sentences_checkpointed(
														    __UpperCAmelCase     ,				__UpperCAmelCase     ,				self.bert_query     ,				__UpperCAmelCase     ,				)
														return self.project_query(__UpperCAmelCase	)




							def 						lowerCamelCase_							(				self:							str     ,				UpperCamelCase__:							int     ,				UpperCamelCase__:							Dict=None     ,				UpperCamelCase__:							Optional[int]=-1     ,				):
														lowerCamelCase__   :      List[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 						lowerCamelCase_							(				self:							Optional[Any]     ,				UpperCamelCase__:							Tuple     ,				UpperCamelCase__:							Optional[int]     ,				UpperCamelCase__:							Dict     ,				UpperCamelCase__:							List[str]     ,				UpperCamelCase__:							Optional[Any] = -1     ,				):
														lowerCamelCase__   :      int			    =			input_ids_query.device
														lowerCamelCase__   :      Union[str, Any]			    =			self.embed_questions(__UpperCAmelCase     ,				__UpperCAmelCase     ,				__UpperCAmelCase	)
														lowerCamelCase__   :      str			    =			self.embed_answers(__UpperCAmelCase     ,				__UpperCAmelCase     ,				__UpperCAmelCase	)
														lowerCamelCase__   :      int			    =			torch.mm(__UpperCAmelCase     ,				a_reps.t()	)
														lowerCamelCase__   :      Optional[Any]			    =			self.ce_loss(__UpperCAmelCase     ,				torch.arange(compare_scores.shape[1]	).to(__UpperCAmelCase	)	)
														lowerCamelCase__   :      Dict			    =			self.ce_loss(compare_scores.t()     ,				torch.arange(compare_scores.shape[0]	).to(__UpperCAmelCase	)	)
														lowerCamelCase__   :      Union[str, Any]			    =			(loss_qa + loss_aq) / 2
														return loss





"""simple docstring"""






import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer


class 	A_       (     tf.keras.layers.Layer   ):





  """simple docstring"""

  def __init__(						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase  ,					__UpperCAmelCase = None  ,					__UpperCAmelCase = None  ,					__UpperCAmelCase = None  ,					__UpperCAmelCase = "longest"  ,					__UpperCAmelCase = True  ,					__UpperCAmelCase = 5_12  ,					__UpperCAmelCase = None  ,					__UpperCAmelCase = True  ,					__UpperCAmelCase = True  ,					__UpperCAmelCase = True  ,					**__UpperCAmelCase  ,					)				->					Union[str, Any]:
     super().__init__()
     if use_fast_bert_tokenizer:
        a   :	int						=    FastBertTokenizer(
            __UpperCAmelCase  ,					token_out_type=tf.intaa  ,					lower_case_nfd_strip_accents=__UpperCAmelCase  ,					**__UpperCAmelCase						)
     else:
        a   :	Optional[Any]						=    tf.lookup.StaticVocabularyTable(
            tf.lookup.KeyValueTensorInitializer(
                keys=__UpperCAmelCase  ,					key_dtype=tf.string  ,					values=tf.range(tf.size(__UpperCAmelCase  ,					out_type=tf.intaa						)  ,					dtype=tf.intaa						)  ,					value_dtype=tf.intaa  ,					)  ,					num_oov_buckets=1  ,					)
        a   :	str						=    BertTokenizerLayer(
            __UpperCAmelCase  ,					token_out_type=tf.intaa  ,					lower_case=__UpperCAmelCase  ,					**__UpperCAmelCase						)

     a   :	str						=    vocab_list
     a   :	Dict						=    do_lower_case
     a   :	Dict						=    cls_token_id or vocab_list.index('[CLS]'						)
     a   :	Tuple						=    sep_token_id or vocab_list.index('[SEP]'						)
     a   :	Optional[Any]						=    pad_token_id or vocab_list.index('[PAD]'						)
     a   :	Tuple						=    ShrinkLongestTrimmer(max_length - 3  ,					axis=1						)  # Allow room for special tokens
     a   :	Union[str, Any]						=    max_length
     a   :	Tuple						=    padding
     a   :	List[Any]						=    truncation
     a   :	Union[str, Any]						=    pad_to_multiple_of
     a   :	List[Any]						=    return_token_type_ids
     a   :	Optional[int]						=    return_attention_mask
  @classmethod
  def 							lowercase_     (						cls  ,					__UpperCAmelCase  ,					**__UpperCAmelCase						)				->					Tuple:  # noqa: F821
     a   :	List[Any]						=    kwargs.pop('do_lower_case'  ,					__UpperCAmelCase						)
     a   :	str						=    tokenizer.do_lower_case if do_lower_case is None else do_lower_case
     a   :	List[Any]						=    kwargs.pop('cls_token_id'  ,					__UpperCAmelCase						)
     a   :	int						=    tokenizer.cls_token_id if cls_token_id is None else cls_token_id
     a   :	Tuple						=    kwargs.pop('sep_token_id'  ,					__UpperCAmelCase						)
     a   :	Optional[int]						=    tokenizer.sep_token_id if sep_token_id is None else sep_token_id
     a   :	List[Any]						=    kwargs.pop('pad_token_id'  ,					__UpperCAmelCase						)
     a   :	Any						=    tokenizer.pad_token_id if pad_token_id is None else pad_token_id

     a   :	Optional[Any]						=    tokenizer.get_vocab()
     a   :	Optional[Any]						=    sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]  ,					key=lambda __UpperCAmelCase						: x[1]						)
     a   :	Optional[Any]						=    [entry[0] for entry in vocab]
     return cls(
         vocab_list=__UpperCAmelCase  ,					do_lower_case=__UpperCAmelCase  ,					cls_token_id=__UpperCAmelCase  ,					sep_token_id=__UpperCAmelCase  ,					pad_token_id=__UpperCAmelCase  ,					**__UpperCAmelCase  ,					)
  @classmethod
  def 							lowercase_     (						cls  ,					__UpperCAmelCase  ,					*__UpperCAmelCase  ,					**__UpperCAmelCase						)				->					Tuple:
     try:
        a   :	Dict						=    BertTokenizer.from_pretrained(__UpperCAmelCase  ,					*__UpperCAmelCase  ,					**__UpperCAmelCase						)
     except:  # noqa: E722
        from .tokenization_bert_fast import BertTokenizerFast

        a   :	Tuple						=    BertTokenizerFast.from_pretrained(__UpperCAmelCase  ,					*__UpperCAmelCase  ,					**__UpperCAmelCase						)
     return cls.from_tokenizer(__UpperCAmelCase  ,					**__UpperCAmelCase						)
  def 							lowercase_     (						self  ,					__UpperCAmelCase						)				->					List[Any]:
     if self.do_lower_case:
        a   :	int						=    case_fold_utfa(__UpperCAmelCase						)
     a   :	Union[str, Any]						=    self.tf_tokenizer.tokenize(__UpperCAmelCase						)
     return tokens.merge_dims(1  ,					-1						)
  def 							lowercase_     (						self  ,					__UpperCAmelCase  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					__UpperCAmelCase=None  ,					)				->					Optional[int]:
     if padding is None:
        a   :	List[Any]						=    self.padding
     if padding not in ("longest", "max_length"):
        raise ValueError('Padding must be either \'longest\' or \'max_length\'!'						)
     if max_length is not None and text_pair is not None:
        # Because we have to instantiate a Trimmer to do it properly
        raise ValueError('max_length cannot be overridden at call time when truncating paired texts!'						)
     if max_length is None:
        a   :	Any						=    self.max_length
     if truncation is None:
        a   :	Any						=    self.truncation
     if pad_to_multiple_of is None:
        a   :	Optional[int]						=    self.pad_to_multiple_of
     if return_token_type_ids is None:
        a   :	str						=    self.return_token_type_ids
     if return_attention_mask is None:
        a   :	Dict						=    self.return_attention_mask
     if not isinstance(__UpperCAmelCase  ,					tf.Tensor						):
        a   :	List[str]						=    tf.convert_to_tensor(__UpperCAmelCase						)
     if text_pair is not None and not isinstance(__UpperCAmelCase  ,					tf.Tensor						):
        a   :	Any						=    tf.convert_to_tensor(__UpperCAmelCase						)
     if text_pair is not None:
        if text.shape.rank > 1:
           raise ValueError('text argument should not be multidimensional when a text pair is supplied!'						)
        if text_pair.shape.rank > 1:
           raise ValueError('text_pair should not be multidimensional!'						)
     if text.shape.rank == 2:
        a	, a   :	Union[str, Any]						=    text[:, 0], text[:, 1]
     a   :	Union[str, Any]						=    self.unpaired_tokenize(__UpperCAmelCase						)
     if text_pair is None:  # Unpaired text
        if truncation:
           a   :	List[Any]						=    text[:, : max_length - 2]  # Allow room for special tokens
        a	, a   :	Dict						=    combine_segments(
            (text,)  ,					start_of_sequence_id=self.cls_token_id  ,					end_of_segment_id=self.sep_token_id						)
     else:  # Paired text
        a   :	Optional[Any]						=    self.unpaired_tokenize(__UpperCAmelCase						)
        if truncation:
           a	, a   :	List[str]						=    self.paired_trimmer.trim([text, text_pair]						)
        a	, a   :	List[Any]						=    combine_segments(
            (text, text_pair)  ,					start_of_sequence_id=self.cls_token_id  ,					end_of_segment_id=self.sep_token_id						)
     if padding == "longest":
        a   :	List[Any]						=    input_ids.bounding_shape(axis=1						)
        if pad_to_multiple_of is not None:
           # No ceiling division in tensorflow, so we negate floordiv instead
           a   :	Optional[int]						=    pad_to_multiple_of * (-tf.math.floordiv(-pad_length  ,					__UpperCAmelCase						))
     else:
        a   :	Any						=    max_length

     a	, a   :	Any						=    pad_model_inputs(__UpperCAmelCase  ,					max_seq_length=__UpperCAmelCase  ,					pad_value=self.pad_token_id						)
     a   :	Optional[Any]						=    {'input_ids': input_ids}
     if return_attention_mask:
        a   :	Tuple						=    attention_mask
     if return_token_type_ids:
        a	, a   :	int						=    pad_model_inputs(
            __UpperCAmelCase  ,					max_seq_length=__UpperCAmelCase  ,					pad_value=self.pad_token_id						)
        a   :	Union[str, Any]						=    token_type_ids
     return output






  def 							lowercase_     (						self						)				->					List[str]:
     return {
         "vocab_list": self.vocab_list,
         "do_lower_case": self.do_lower_case,
         "cls_token_id": self.cls_token_id,
         "sep_token_id": self.sep_token_id,
         "pad_token_id": self.pad_token_id,
     }





