from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCamelCase													=		logging.get_logger(__name__)

UpperCamelCase													=		{
    '''google/mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json'''
}



class 						snake_case_ (	__A ):
   __A			:	Tuple        =       MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
   __A			:	List[str]        =       "mobilebert"






   def __init__(   self       :  Tuple			,		lowercase_       :  List[str]=3_05_22			,		lowercase_       :  Any=5_12			,		lowercase_       :  List[str]=24			,		lowercase_       :  Optional[int]=4			,		lowercase_       :  Optional[int]=5_12			,		lowercase_       :  Optional[int]="relu"			,		lowercase_       :  Dict=0.0			,		lowercase_       :  Optional[Any]=0.1			,		lowercase_       :  List[Any]=5_12			,		lowercase_       :  Union[str, Any]=2			,		lowercase_       :  Optional[int]=0.02			,		lowercase_       :  str=1E-12			,		lowercase_       :  List[Any]=0			,		lowercase_       :  str=1_28			,		lowercase_       :  int=True			,		lowercase_       :  Dict=True			,		lowercase_       :  Tuple=1_28			,		lowercase_       :  Tuple=False			,		lowercase_       :  Optional[int]=True			,		lowercase_       :  Any=4			,		lowercase_       :  List[str]="no_norm"			,		lowercase_       :  Union[str, Any]=True			,		lowercase_       :  Optional[int]=None			,		**lowercase_       :  Any			,		)      ->		List[str]:
       super().__init__(pad_token_id=lowercase_			,		**lowercase_						)

       lowercase__				:     Tuple					      =       vocab_size
       lowercase__				:     int					      =       hidden_size
       lowercase__				:     Any					      =       num_hidden_layers
       lowercase__				:     Any					      =       num_attention_heads
       lowercase__				:     List[str]					      =       hidden_act
       lowercase__				:     Union[str, Any]					      =       intermediate_size
       lowercase__				:     List[Any]					      =       hidden_dropout_prob
       lowercase__				:     List[Any]					      =       attention_probs_dropout_prob
       lowercase__				:     List[str]					      =       max_position_embeddings
       lowercase__				:     List[str]					      =       type_vocab_size
       lowercase__				:     Optional[Any]					      =       initializer_range
       lowercase__				:     Union[str, Any]					      =       layer_norm_eps
       lowercase__				:     int					      =       embedding_size
       lowercase__				:     int					      =       trigram_input
       lowercase__				:     Tuple					      =       use_bottleneck
       lowercase__				:     int					      =       intra_bottleneck_size
       lowercase__				:     Optional[int]					      =       use_bottleneck_attention
       lowercase__				:     int					      =       key_query_shared_bottleneck
       lowercase__				:     Any					      =       num_feedforward_networks
       lowercase__				:     str					      =       normalization_type
       lowercase__				:     Optional[int]					      =       classifier_activation

       if self.use_bottleneck:
           lowercase__				:     str					      =       intra_bottleneck_size
       else:
           lowercase__				:     Optional[int]					      =       hidden_size

       lowercase__				:     Any					      =       classifier_dropout



class 						snake_case_ (	__A ):






   @property
   def    __UpperCamelCase  (   self       :  List[str]						)      ->		Mapping[str, Mapping[int, str]]:
       if self.task == "multiple-choice":
           lowercase__				:     List[Any]					      =       {0: "batch", 1: "choice", 2: "sequence"}
       else:
           lowercase__				:     int					      =       {0: "batch", 1: "sequence"}
       return OrderedDict(
           [
               ("input_ids", dynamic_axis),
               ("attention_mask", dynamic_axis),
               ("token_type_ids", dynamic_axis),
           ]						)




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

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



class 						snake_case_ (	__A ):
   __A			:	Optional[Any]        =       RetriBertConfig
   __A			:	str        =       None
   __A			:	Any        =       "retribert"






   def    __UpperCamelCase  (   self       :  Dict			,		lowercase_       :  List[Any]						)      ->		List[str]:
       if isinstance(lowercase_			,		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(lowercase_			,		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(lowercase_			,		nn.LayerNorm						):
           module.bias.data.zero_()
           module.weight.data.fill_(1.0						)



UpperCamelCase													=		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."						,__A						,)
class 						snake_case_ (	__A ):






   def __init__(   self       :  Dict			,		lowercase_       :  RetriBertConfig						)      ->		None:
       super().__init__(lowercase_						)
       lowercase__				:     str					      =       config.projection_dim

       lowercase__				:     Optional[int]					      =       BertModel(lowercase_						)
       lowercase__				:     Union[str, Any]					      =       None if config.share_encoders else BertModel(lowercase_						)
       lowercase__				:     Tuple					      =       nn.Dropout(config.hidden_dropout_prob						)
       lowercase__				:     Any					      =       nn.Linear(config.hidden_size			,		config.projection_dim			,		bias=lowercase_						)
       lowercase__				:     str					      =       nn.Linear(config.hidden_size			,		config.projection_dim			,		bias=lowercase_						)

       lowercase__				:     Optional[Any]					      =       nn.CrossEntropyLoss(reduction="mean"						)

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






   def    __UpperCamelCase  (   self       :  Dict			,		lowercase_       :  str			,		lowercase_       :  Optional[int]			,		lowercase_       :  Tuple			,		lowercase_       :  Optional[int]=-1			,		)      ->		List[str]:
       # reproduces BERT forward pass with checkpointing
       if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
           return sent_encoder(lowercase_			,		attention_mask=lowercase_						)[1]
       else:
           # prepare implicit variables
           lowercase__				:     Union[str, Any]					      =       input_ids.device
           lowercase__				:     Union[str, Any]					      =       input_ids.size()
           lowercase__				:     int					      =       torch.zeros(lowercase_			,		dtype=torch.long			,		device=lowercase_						)
           lowercase__				:     List[Any]					      =       [None] * sent_encoder.config.num_hidden_layers
           lowercase__				:     torch.Tensor					      =       sent_encoder.get_extended_attention_mask(
               lowercase_			,		lowercase_						)

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

           # run embedding layer on everything at once
           lowercase__				:     Optional[int]					      =       sent_encoder.embeddings(
               input_ids=lowercase_			,		position_ids=lowercase_			,		token_type_ids=lowercase_			,		inputs_embeds=lowercase_						)
           # run encoding and pooling on one mini-batch at a time
           lowercase__				:     str					      =       []
           for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size						)						):
               lowercase__				:     int					      =       embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
               lowercase__				:     int					      =       extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
               lowercase__				:     int					      =       checkpoint.checkpoint(lowercase_			,		lowercase_			,		lowercase_						)
               pooled_output_list.append(lowercase_						)
           return torch.cat(lowercase_			,		dim=0						)






   def    __UpperCamelCase  (   self       :  Optional[Any]			,		lowercase_       :  Any			,		lowercase_       :  Any=None			,		lowercase_       :  Union[str, Any]=-1			,		)      ->		List[str]:
       lowercase__				:     Optional[Any]					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query			,		lowercase_			,		)
       return self.project_query(lowercase_						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Union[str, Any]=None			,		lowercase_       :  Dict=-1			,		)      ->		Optional[int]:
       lowercase__				:     str					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query if self.bert_doc is None else self.bert_doc			,		lowercase_			,		)
       return self.project_doc(lowercase_						)







   def    __UpperCamelCase  (   self       :  str			,		lowercase_       :  torch.LongTensor			,		lowercase_       :  Optional[torch.FloatTensor]			,		lowercase_       :  torch.LongTensor			,		lowercase_       :  Optional[torch.FloatTensor]			,		lowercase_       :  int = -1			,		)      ->		torch.FloatTensor:
       lowercase__				:     Tuple					      =       input_ids_query.device
       lowercase__				:     str					      =       self.embed_questions(lowercase_			,		lowercase_			,		lowercase_						)
       lowercase__				:     Any					      =       self.embed_answers(lowercase_			,		lowercase_			,		lowercase_						)
       lowercase__				:     List[str]					      =       torch.mm(lowercase_			,		a_reps.t()						)
       lowercase__				:     Optional[int]					      =       self.ce_loss(lowercase_			,		torch.arange(compare_scores.shape[1]						).to(lowercase_						)						)
       lowercase__				:     str					      =       self.ce_loss(compare_scores.t()			,		torch.arange(compare_scores.shape[0]						).to(lowercase_						)						)
       lowercase__				:     Tuple					      =       (loss_qa + loss_aq) / 2
       return loss



