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

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

class 			lowerCamelCase_			(snake_case__					):
      '''simple docstring'''

      __UpperCamelCase:						str      			=		RetriBertConfig
      __UpperCamelCase:						Any      			=		None
      __UpperCamelCase:						int      			=		"retribert"




      def   _A			( self		:       List[Any]		,      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 )

__SCREAMING_SNAKE_CASE :  Tuple  =						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."							,				snake_case__							,				)
class 			lowerCamelCase_			(snake_case__					):
      '''simple docstring'''

      def __init__( self		:       Dict		,      A		:       RetriBertConfig ):
             super().__init__(A )
             _UpperCAmelCase  :						Optional[int]							   =					config.projection_dim

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

             _UpperCAmelCase  :						Any							   =					nn.CrossEntropyLoss(reduction="mean" )

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




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

                    # define function for checkpointing
                    def partial_encode(*A		:       Optional[Any] ):
                           _UpperCAmelCase  :						Union[str, Any]							   =					sent_encoder.encoder(
                               inputs[0]		,      attention_mask=inputs[1]		,      head_mask=A		,      )
                           _UpperCAmelCase  :						Optional[int]							   =					encoder_outputs[0]
                           _UpperCAmelCase  :						Tuple							   =					sent_encoder.pooler(A )
                           return pooled_output

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




      def   _A			( self		:       Dict		,      A		:       Any		,      A		:       Dict=None		,      A		:       int=-1		,      ):
             _UpperCAmelCase  :						Tuple							   =					self.embed_sentences_checkpointed(
                 A		,      A		,      self.bert_query		,      A		,      )
             return self.project_query(A )




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


'''simple docstring'''




import platform
from argparse import ArgumentParser

import huggingface_hub
import pandas
import pyarrow

from datasets import __version__ as version
from datasets.commands import BaseDatasetsCLICommand

def 			UpperCamelCase_							(      _UpperCAmelCase						:   List[str]					)					->					Union[str, Any]:


       """simple docstring"""







       return EnvironmentCommand()


class 			lowerCamelCase_			(snake_case__					):
      '''simple docstring'''

      @staticmethod
      def   _A			( A		:       ArgumentParser ):
             _UpperCAmelCase  :						List[str]							   =					parser.add_parser("env"		,      help="Print relevant system environment info." )
             download_parser.set_defaults(func=A )




      def   _A			( self		:       List[str] ):
             _UpperCAmelCase  :						str							   =					{
                 "`datasets` version": version,
                 "Platform": platform.platform(),
                 "Python version": platform.python_version(),
                 "Huggingface_hub version": huggingface_hub.__version__,
                 "PyArrow version": pyarrow.__version__,
                 "Pandas version": pandas.__version__,
             }

             print("\nCopy-and-paste the text below in your GitHub issue.\n" )
             print(self.format_dict(A ) )

             return info





      @staticmethod
      def   _A			( A		:       Tuple ):
             return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"

