






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


SCREAMING_SNAKE_CASE_				      =							logging.get_logger(__name__)

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




class 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







   _A						=   RetriBertConfig
   _A						=   None
   _A						=   'retribert'



   def    __magic_name__    ( self   ,   _A			)    ->   Optional[int]:
    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			)
SCREAMING_SNAKE_CASE_				      =							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 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







   def __init__( self   ,   _A			)    ->   None:
    super().__init__(_A			)
    __a    :	Union[str, Any]									=						config.projection_dim

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

    __a    :	Union[str, Any]									=						nn.CrossEntropyLoss(reduction='mean'			)

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



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A   ,   _A=-1   ,   )    ->   Optional[int]:
    # 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
     __a    :	int									=						input_ids.device
     __a    :	Union[str, Any]									=						input_ids.size()
     __a    :	Tuple									=						torch.zeros(_A   ,   dtype=torch.long   ,   device=_A			)
     __a    :	Union[str, Any]									=						[None] * sent_encoder.config.num_hidden_layers
     __a    :	torch.Tensor									=						sent_encoder.get_extended_attention_mask(
         _A   ,   _A			)

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

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



   def    __magic_name__    ( self   ,   _A   ,   _A=None   ,   _A=-1   ,   )    ->   int:
    __a    :	str									=						self.embed_sentences_checkpointed(
        _A   ,   _A   ,   self.bert_query   ,   _A   ,   )
    return self.project_query(_A			)



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












'''simple docstring'''


from collections import OrderedDict
from typing import Mapping

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


SCREAMING_SNAKE_CASE_				      =							logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_				      =							{
    "squeezebert/squeezebert-uncased": (
        "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/config.json"
    ),
    "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/config.json",
    "squeezebert/squeezebert-mnli-headless": (
        "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/config.json"
    ),
}




class 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







   _A						=   SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
   _A						=   'squeezebert'



   def __init__( self   ,   _A=30522   ,   _A=768   ,   _A=12   ,   _A=12   ,   _A=3072   ,   _A="gelu"   ,   _A=0.1   ,   _A=0.1   ,   _A=512   ,   _A=2   ,   _A=0.02   ,   _A=1E-1_2   ,   _A=0   ,   _A=768   ,   _A=4   ,   _A=4   ,   _A=4   ,   _A=1   ,   _A=4   ,   _A=4   ,   **_A   ,   )    ->   List[Any]:
    super().__init__(pad_token_id=_A   ,   **_A			)

    __a    :	Optional[int]									=						vocab_size
    __a    :	Optional[int]									=						hidden_size
    __a    :	int									=						num_hidden_layers
    __a    :	int									=						num_attention_heads
    __a    :	Tuple									=						hidden_act
    __a    :	Optional[Any]									=						intermediate_size
    __a    :	Any									=						hidden_dropout_prob
    __a    :	List[Any]									=						attention_probs_dropout_prob
    __a    :	List[str]									=						max_position_embeddings
    __a    :	Tuple									=						type_vocab_size
    __a    :	Tuple									=						initializer_range
    __a    :	List[str]									=						layer_norm_eps
    __a    :	str									=						embedding_size
    __a    :	Any									=						q_groups
    __a    :	Any									=						k_groups
    __a    :	Union[str, Any]									=						v_groups
    __a    :	List[str]									=						post_attention_groups
    __a    :	Dict									=						intermediate_groups
    __a    :	Optional[Any]									=						output_groups




class 							lowerCAmelCase					(							lowerCamelCase__   ):







   """simple docstring"""







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




