




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


_lowerCamelCase							=      logging.get_logger(__name__)

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


class        UpperCAmelCase__				(							UpperCAmelCase__				):



     '''simple docstring'''
     _SCREAMING_SNAKE_CASE      :					Dict     					=    RetriBertConfig
     _SCREAMING_SNAKE_CASE      :					Optional[int]     					=    None
     _SCREAMING_SNAKE_CASE      :					Optional[Any]     					=    "retribert"
     def        lowerCAmelCase__  (				self ,    _lowerCAmelCase	):
            if isinstance(_lowerCAmelCase ,    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(_lowerCAmelCase ,    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(_lowerCAmelCase ,    nn.LayerNorm	):
                   module.bias.data.zero_()
                   module.weight.data.fill_(1.0	)



_lowerCamelCase							=      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        UpperCAmelCase__				(							UpperCAmelCase__				):



     '''simple docstring'''
     def __init__(				self ,    _lowerCAmelCase	):
            super().__init__(_lowerCAmelCase	)
            a			   =config.projection_dim

            a			   =BertModel(_lowerCAmelCase	)
            a			   =None if config.share_encoders else BertModel(_lowerCAmelCase	)
            a			   =nn.Dropout(config.hidden_dropout_prob	)
            a			   =nn.Linear(config.hidden_size ,    config.projection_dim ,    bias=_lowerCAmelCase	)
            a			   =nn.Linear(config.hidden_size ,    config.projection_dim ,    bias=_lowerCAmelCase	)

            a			   =nn.CrossEntropyLoss(reduction="""mean"""	)

            # Initialize weights and apply final processing
            self.post_init()
     def        lowerCAmelCase__  (				self ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase=-1 ,    ):
            # reproduces BERT forward pass with checkpointing
            if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
                   return sent_encoder(_lowerCAmelCase ,    attention_mask=_lowerCAmelCase	)[1]
            else:
                   # prepare implicit variables
                   a			   =input_ids.device
                   a			   =input_ids.size()
                   a			   =torch.zeros(_lowerCAmelCase ,    dtype=torch.long ,    device=_lowerCAmelCase	)
                   a			   =[None] * sent_encoder.config.num_hidden_layers
                   a			   =sent_encoder.get_extended_attention_mask(
                       _lowerCAmelCase ,    _lowerCAmelCase	)

                   # define function for checkpointing
                   def partial_encode(*_lowerCAmelCase	):
                          a			   =sent_encoder.encoder(
                              inputs[0] ,    attention_mask=inputs[1] ,    head_mask=_lowerCAmelCase ,    )
                          a			   =encoder_outputs[0]
                          a			   =sent_encoder.pooler(_lowerCAmelCase	)
                          return pooled_output

                   # run embedding layer on everything at once
                   a			   =sent_encoder.embeddings(
                       input_ids=_lowerCAmelCase ,    position_ids=_lowerCAmelCase ,    token_type_ids=_lowerCAmelCase ,    inputs_embeds=_lowerCAmelCase	)
                   # run encoding and pooling on one mini-batch at a time
                   a			   =[]
                   for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size	)	):
                          a			   =embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                          a			   =extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                          a			   =checkpoint.checkpoint(_lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase	)
                          pooled_output_list.append(_lowerCAmelCase	)
                   return torch.cat(_lowerCAmelCase ,    dim=0	)
     def        lowerCAmelCase__  (				self ,    _lowerCAmelCase ,    _lowerCAmelCase=None ,    _lowerCAmelCase=-1 ,    ):
            a			   =self.embed_sentences_checkpointed(
                _lowerCAmelCase ,    _lowerCAmelCase ,    self.bert_query ,    _lowerCAmelCase ,    )
            return self.project_query(_lowerCAmelCase	)
     def        lowerCAmelCase__  (				self ,    _lowerCAmelCase ,    _lowerCAmelCase=None ,    _lowerCAmelCase=-1 ,    ):
            a			   =self.embed_sentences_checkpointed(
                _lowerCAmelCase ,    _lowerCAmelCase ,    self.bert_query if self.bert_doc is None else self.bert_doc ,    _lowerCAmelCase ,    )
            return self.project_doc(_lowerCAmelCase	)






     def        lowerCAmelCase__  (				self ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase = -1 ,    ):
            a			   =input_ids_query.device
            a			   =self.embed_questions(_lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase	)
            a			   =self.embed_answers(_lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase	)
            a			   =torch.mm(_lowerCAmelCase ,    a_reps.t()	)
            a			   =self.ce_loss(_lowerCAmelCase ,    torch.arange(compare_scores.shape[1]	).to(_lowerCAmelCase	)	)
            a			   =self.ce_loss(compare_scores.t() ,    torch.arange(compare_scores.shape[0]	).to(_lowerCAmelCase	)	)
            a			   =(loss_qa + loss_aq) / 2
            return loss






import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase							=      logging.get_logger(__name__)

_lowerCamelCase							=      {
    '''facebook/hubert-base-ls960''': '''https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json''',
    # See all Hubert models at https://huggingface.co/models?filter=hubert
}


class        UpperCAmelCase__				(							UpperCAmelCase__				):



     '''simple docstring'''
     _SCREAMING_SNAKE_CASE      :					Dict     					=    "hubert"
     def __init__(				self ,    _lowerCAmelCase=32 ,    _lowerCAmelCase=768 ,    _lowerCAmelCase=12 ,    _lowerCAmelCase=12 ,    _lowerCAmelCase=3_072 ,    _lowerCAmelCase="gelu" ,    _lowerCAmelCase=0.1 ,    _lowerCAmelCase=0.1 ,    _lowerCAmelCase=0.1 ,    _lowerCAmelCase=True ,    _lowerCAmelCase=0.0 ,    _lowerCAmelCase=0.1 ,    _lowerCAmelCase=0.1 ,    _lowerCAmelCase=0.02 ,    _lowerCAmelCase=1E-5 ,    _lowerCAmelCase="group" ,    _lowerCAmelCase="gelu" ,    _lowerCAmelCase=(512, 512, 512, 512, 512, 512, 512) ,    _lowerCAmelCase=(5, 2, 2, 2, 2, 2, 2) ,    _lowerCAmelCase=(10, 3, 3, 3, 3, 2, 2) ,    _lowerCAmelCase=False ,    _lowerCAmelCase=128 ,    _lowerCAmelCase=16 ,    _lowerCAmelCase=False ,    _lowerCAmelCase=True ,    _lowerCAmelCase=0.05 ,    _lowerCAmelCase=10 ,    _lowerCAmelCase=2 ,    _lowerCAmelCase=0.0 ,    _lowerCAmelCase=10 ,    _lowerCAmelCase=0 ,    _lowerCAmelCase="sum" ,    _lowerCAmelCase=False ,    _lowerCAmelCase=False ,    _lowerCAmelCase=256 ,    _lowerCAmelCase=0 ,    _lowerCAmelCase=1 ,    _lowerCAmelCase=2 ,    **_lowerCAmelCase ,    ):
            super().__init__(**_lowerCAmelCase ,    pad_token_id=_lowerCAmelCase ,    bos_token_id=_lowerCAmelCase ,    eos_token_id=_lowerCAmelCase	)
            a			   =hidden_size
            a			   =feat_extract_norm
            a			   =feat_extract_activation
            a			   =list(_lowerCAmelCase	)
            a			   =list(_lowerCAmelCase	)
            a			   =list(_lowerCAmelCase	)
            a			   =conv_bias
            a			   =num_conv_pos_embeddings
            a			   =num_conv_pos_embedding_groups
            a			   =len(self.conv_dim	)
            a			   =num_hidden_layers
            a			   =intermediate_size
            a			   =hidden_act
            a			   =num_attention_heads
            a			   =hidden_dropout
            a			   =attention_dropout
            a			   =activation_dropout
            a			   =feat_proj_layer_norm
            a			   =feat_proj_dropout
            a			   =final_dropout
            a			   =layerdrop
            a			   =layer_norm_eps
            a			   =initializer_range
            a			   =vocab_size
            a			   =do_stable_layer_norm
            a			   =use_weighted_layer_sum
            a			   =classifier_proj_size

            if (
                (len(self.conv_stride	) != self.num_feat_extract_layers)
                or (len(self.conv_kernel	) != self.num_feat_extract_layers)
                or (len(self.conv_dim	) != self.num_feat_extract_layers)
            ):
                   raise ValueError(
                       """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                       """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                       F''' {len(self.conv_dim	)}`, `len(config.conv_stride) = {len(self.conv_stride	)}`,'''
                       F''' `len(config.conv_kernel) = {len(self.conv_kernel	)}`.'''	)

            # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
            a			   =apply_spec_augment
            a			   =mask_time_prob
            a			   =mask_time_length
            a			   =mask_time_min_masks
            a			   =mask_feature_prob
            a			   =mask_feature_length
            a			   =mask_feature_min_masks

            # ctc loss
            a			   =ctc_loss_reduction
            a			   =ctc_zero_infinity






     @property
     def        lowerCAmelCase__  (				self	):
            return functools.reduce(operator.mul ,    self.conv_stride ,    1	)
