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


A     :   Optional[Any]           =   logging.get_logger(__name__)

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



class  lowerCAmelCase__   (       lowerCAmelCase__       ):



  '''simple docstring'''






  _UpperCamelCase						= RetriBertConfig
  _UpperCamelCase						= None
  _UpperCamelCase						= 'retribert'

  def 		_lowerCamelCase	(self  : Optional[Any]	, lowerCAmelCase_  : Union[str, Any]    )   ->       List[str]:

        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[int]           =   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  : List[Any]	, lowerCAmelCase_  : List[Any]    )   ->       Tuple:
        super().__init__(_lowerCamelCase    )
        snake_case_						       =							config.projection_dim

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

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

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

  def 		_lowerCamelCase	(self  : Any	, lowerCAmelCase_  : List[Any]	, lowerCAmelCase_  : List[Any]	, lowerCAmelCase_  : Any	, lowerCAmelCase_  : Optional[int]=-1	, )   ->       int:

        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
              snake_case_						       =							input_ids.device
              snake_case_						       =							input_ids.size()
              snake_case_						       =							torch.zeros(_lowerCamelCase	, dtype=torch.long	, device=_lowerCamelCase    )
              snake_case_						       =							[None] * sent_encoder.config.num_hidden_layers
              snake_case_						       =							sent_encoder.get_extended_attention_mask(
                  _lowerCamelCase	, _lowerCamelCase    )

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

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

  def 		_lowerCamelCase	(self  : Dict	, lowerCAmelCase_  : Union[str, Any]	, lowerCAmelCase_  : Tuple=None	, lowerCAmelCase_  : Optional[int]=-1	, )   ->       str:
        snake_case_						       =							self.embed_sentences_checkpointed(
            _lowerCamelCase	, _lowerCamelCase	, self.bert_query	, _lowerCamelCase	, )
        return self.project_query(_lowerCamelCase    )

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



'''simple docstring'''





from __future__ import annotations

A           =   [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]



class  lowerCAmelCase__   :



  '''simple docstring'''






  def __init__(self  : Optional[int]	, lowerCAmelCase_  : int    )   ->       None:
        snake_case_						       =							-1
        snake_case_						       =							-1
        snake_case_						       =							[-1] * length
        snake_case_						       =							None
        snake_case_						       =							None


  def __repr__(self  : List[Any]    )   ->       str:
        return f'''Node(min_value={self.minn} max_value={self.maxx})'''

def   snake_case_       (							_a     :							list[int]			):
      snake_case_						       =							Node(len(_a			)			)
      snake_case_       ,	snake_case_						       =							min(_a			), max(_a			)
      # Leaf node case where the node contains only one unique value
      if root.minn == root.maxx:
            return root
      snake_case_						       =							(root.minn + root.maxx) // 2

      snake_case_						       =							[]
      snake_case_						       =							[]

      for index, num in enumerate(_a			):
            if num <= pivot:
                  left_arr.append(_a			)
            else:
                  right_arr.append(_a			)
            snake_case_						       =							len(_a			)
      snake_case_						       =							build_tree(_a			)
      snake_case_						       =							build_tree(_a			)
      return root
def   snake_case_       (							_a     :							Node | None ,					_a     :							int ,					_a     :							int			):
      if index < 0 or node is None:
            return 0
      # Leaf node cases
      if node.minn == node.maxx:
            return index + 1 if node.minn == num else 0
      snake_case_						       =							(node.minn + node.maxx) // 2
      if num <= pivot:
            # go the left subtree and map index to the left subtree
            return rank_till_index(node.left ,					_a ,					node.map_left[index] - 1			)
      else:
            # go to the right subtree and map index to the right subtree
            return rank_till_index(node.right ,					_a ,					index - node.map_left[index]			)
def   snake_case_       (							_a     :							Node | None ,					_a     :							int ,					_a     :							int ,					_a     :							int			):
      if start > end:
            return 0
      snake_case_						       =							rank_till_index(_a ,					_a ,					_a			)
      snake_case_						       =							rank_till_index(_a ,					_a ,					start - 1			)
      return rank_till_end - rank_before_start
def   snake_case_       (							_a     :							Node | None ,					_a     :							int ,					_a     :							int ,					_a     :							int			):
      if index > (end - start) or start > end or node is None:
            return -1
      # Leaf node case
      if node.minn == node.maxx:
            return node.minn
      # Number of elements in the left subtree in interval [start, end]
      snake_case_						       =							node.map_left[end] - (
          node.map_left[start - 1] if start else 0
      )
      if num_elements_in_left_tree > index:
            return quantile(
                node.left ,					_a ,					(node.map_left[start - 1] if start else 0) ,					node.map_left[end] - 1 ,					)
      else:
            return quantile(
                node.right ,					index - num_elements_in_left_tree ,					start - (node.map_left[start - 1] if start else 0) ,					end - node.map_left[end] ,					)
def   snake_case_       (							_a     :							Node | None ,					_a     :							int ,					_a     :							int ,					_a     :							int ,					_a     :							int			):
      if (
          start > end
          or node is None
          or start_num > end_num
          or node.minn > end_num
          or node.maxx < start_num
      ):
            return 0
      if start_num <= node.minn and node.maxx <= end_num:
            return end - start + 1
      snake_case_						       =							range_counting(
          node.left ,					(node.map_left[start - 1] if start else 0) ,					node.map_left[end] - 1 ,					_a ,					_a ,					)
      snake_case_						       =							range_counting(
          node.right ,					start - (node.map_left[start - 1] if start else 0) ,					end - node.map_left[end] ,					_a ,					_a ,					)
      return left + right


if __name__ == "__main__":
     import doctest

     doctest.testmod()

