
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


a__				:      List[str]    		=     logging.get_logger(__name__)

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






class     a_       (			a__							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  RetriBertConfig
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  None
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  'retribert'






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase   )					->Dict:
           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   )





a__				:      Optional[Any]    		=     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     a_       (			a__							):



       """simple docstring"""






       def __init__(		self				,       _lowerCamelCase   )					->None:
           super().__init__(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = config.projection_dim

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

           SCREAMING_SNAKE_CASE				:				Dict				      = nn.CrossEntropyLoss(reduction='''mean'''   )

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






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase				,       _lowerCamelCase=-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(_lowerCamelCase				,       attention_mask=_lowerCamelCase   )[1]
           else:
               # prepare implicit variables
               SCREAMING_SNAKE_CASE				:				Optional[Any]				      = input_ids.device
               SCREAMING_SNAKE_CASE				:				Any				      = input_ids.size()
               SCREAMING_SNAKE_CASE				:				List[Any]				      = torch.zeros(_lowerCamelCase				,       dtype=torch.long				,       device=_lowerCamelCase   )
               SCREAMING_SNAKE_CASE				:				Dict				      = [None] * sent_encoder.config.num_hidden_layers
               SCREAMING_SNAKE_CASE				:				torch.Tensor				      = sent_encoder.get_extended_attention_mask(
                   _lowerCamelCase				,       _lowerCamelCase   )

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

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






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase=None				,       _lowerCamelCase=-1				,       )					->Optional[int]:
           SCREAMING_SNAKE_CASE				:				int				      = self.embed_sentences_checkpointed(
               _lowerCamelCase				,       _lowerCamelCase				,       self.bert_query				,       _lowerCamelCase				,       )
           return self.project_query(_lowerCamelCase   )






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


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


a__				:      List[Any]    		=     {
    '''configuration_decision_transformer''': [
        '''DECISION_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''DecisionTransformerConfig''',
    ],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      a__				:      List[str]    		=     [
          '''DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
          '''DecisionTransformerGPT2Model''',
          '''DecisionTransformerGPT2PreTrainedModel''',
          '''DecisionTransformerModel''',
          '''DecisionTransformerPreTrainedModel''',
      ]


if TYPE_CHECKING:
      from .configuration_decision_transformer import (
          DECISION_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
          DecisionTransformerConfig,
      )

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_decision_transformer import (
                DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
                DecisionTransformerGPTaModel,
                DecisionTransformerGPTaPreTrainedModel,
                DecisionTransformerModel,
                DecisionTransformerPreTrainedModel,
            )


else:
      import sys

      a__				:      str    		=     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
