




'''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


lowercase__								=						logging.get_logger(__name__)

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






class     lowercase  ( UpperCAmelCase_):
      __lowercase					=	RetriBertConfig
      __lowercase					=	None
      __lowercase					=	'''retribert'''






      def  A__(self			,	a__       )							-> str:
         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       )

lowercase__								=						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     lowercase  ( UpperCAmelCase_):






      def __init__(self			,	a__       )							-> None:
         super().__init__(a__       )
         SCREAMING_SNAKE_CASE__      :					Any							    =			config.projection_dim

         SCREAMING_SNAKE_CASE__      :					str							    =			BertModel(a__       )
         SCREAMING_SNAKE_CASE__      :					Dict							    =			None if config.share_encoders else BertModel(a__       )
         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			nn.Dropout(config.hidden_dropout_prob       )
         SCREAMING_SNAKE_CASE__      :					Any							    =			nn.Linear(config.hidden_size			,	config.projection_dim			,	bias=a__       )
         SCREAMING_SNAKE_CASE__      :					str							    =			nn.Linear(config.hidden_size			,	config.projection_dim			,	bias=a__       )

         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			nn.CrossEntropyLoss(reduction='''mean'''       )

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






      def  A__(self			,	a__			,	a__			,	a__			,	a__=-1			,	)							-> str:
         # 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
            SCREAMING_SNAKE_CASE__      :					List[Any]							    =			input_ids.device
            SCREAMING_SNAKE_CASE__      :					List[str]							    =			input_ids.size()
            SCREAMING_SNAKE_CASE__      :					Any							    =			torch.zeros(a__			,	dtype=torch.long			,	device=a__       )
            SCREAMING_SNAKE_CASE__      :					Tuple							    =			[None] * sent_encoder.config.num_hidden_layers
            SCREAMING_SNAKE_CASE__      :					torch.Tensor							    =			sent_encoder.get_extended_attention_mask(
                a__			,	a__       )

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

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






      def  A__(self			,	a__			,	a__=None			,	a__=-1			,	)							-> Any:
         SCREAMING_SNAKE_CASE__      :					Any							    =			self.embed_sentences_checkpointed(
             a__			,	a__			,	self.bert_query			,	a__			,	)
         return self.project_query(a__       )






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







'''simple docstring'''





from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class     lowercase  ( UpperCAmelCase_):
      __lowercase					=	['''image_processor''', '''tokenizer''']
      __lowercase					=	'''EfficientNetImageProcessor'''
      __lowercase					=	('''BertTokenizer''', '''BertTokenizerFast''')






      def __init__(self			,	a__			,	a__       )							-> Tuple:
         super().__init__(a__			,	a__       )






      def __call__(self			,	a__=None			,	a__=None			,	a__="max_length"			,	a__=6_4			,	a__=None			,	**a__       )							-> Any:
         if text is None and images is None:
            raise ValueError('''You have to specify either text or images. Both cannot be none.'''       )

         if text is not None:
            SCREAMING_SNAKE_CASE__      :					List[Any]							    =			self.tokenizer(
                a__			,	padding=a__			,	max_length=a__			,	return_tensors=a__			,	**a__       )

         if images is not None:
            SCREAMING_SNAKE_CASE__      :					Any							    =			self.image_processor(a__			,	return_tensors=a__			,	**a__       )

         if text is not None and images is not None:
            SCREAMING_SNAKE_CASE__      :					str							    =			image_features.pixel_values
            return encoding
         elif text is not None:
            return encoding
         else:
            return BatchEncoding(data=dict(**a__       )			,	tensor_type=a__       )






      def  A__(self			,	*a__			,	**a__       )							-> str:
         return self.tokenizer.batch_decode(*a__			,	**a__       )






      def  A__(self			,	*a__			,	**a__       )							-> str:
         return self.tokenizer.decode(*a__			,	**a__       )






      @property
      def  A__(self       )							-> Optional[int]:
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			self.tokenizer.model_input_names
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			self.image_processor.model_input_names
         return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names       )       )

