import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter



class 						snake_case_ (	TensorFormatter[Mapping, np.ndarray, Mapping] ):






   def __init__(   self       :  Union[str, Any]			,		lowercase_       :  List[Any]=None			,		**lowercase_       :  List[Any]						)      ->		Tuple:
       super().__init__(features=lowercase_						)
       lowercase__				:     Dict					      =       np_array_kwargs






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  str						)      ->		str:
       if isinstance(lowercase_			,		lowercase_						):
           if column and all(
               isinstance(lowercase_			,		np.ndarray						) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column						):
               return np.stack(lowercase_						)
           else:
               # don't use np.array(column, dtype=object)
               # since it fails in certain cases
               # see https://stackoverflow.com/q/51005699
               lowercase__				:     Any					      =       np.empty(len(lowercase_						)			,		dtype=lowercase_						)
               lowercase__				:     Tuple					      =       column
               return out
       return column






   def    __UpperCamelCase  (   self       :  Tuple			,		lowercase_       :  Dict						)      ->		Union[str, Any]:
       if isinstance(lowercase_			,		(str, bytes, type(lowercase_						))						):
           return value
       elif isinstance(lowercase_			,		(np.character, np.ndarray)						) and np.issubdtype(value.dtype			,		np.character						):
           return value
       elif isinstance(lowercase_			,		np.number						):
           return value

       lowercase__				:     Any					      =       {}

       if isinstance(lowercase_			,		np.ndarray						) and np.issubdtype(value.dtype			,		np.integer						):
           lowercase__				:     Tuple					      =       {"dtype": np.intaa}
       elif isinstance(lowercase_			,		np.ndarray						) and np.issubdtype(value.dtype			,		np.floating						):
           lowercase__				:     Optional[int]					      =       {"dtype": np.floataa}
       elif config.PIL_AVAILABLE and "PIL" in sys.modules:
           import PIL.Image

           if isinstance(lowercase_			,		PIL.Image.Image						):
               return np.asarray(lowercase_			,		**self.np_array_kwargs						)

       return np.asarray(lowercase_			,		**{**default_dtype, **self.np_array_kwargs}						)






   def    __UpperCamelCase  (   self       :  Optional[Any]			,		lowercase_       :  Union[str, Any]						)      ->		Tuple:
       # support for torch, tf, jax etc.
       if config.TORCH_AVAILABLE and "torch" in sys.modules:
           import torch

           if isinstance(lowercase_			,		torch.Tensor						):
               return self._tensorize(data_struct.detach().cpu().numpy()[()]						)
       if hasattr(lowercase_			,		"__array__"						) and not isinstance(lowercase_			,		(np.ndarray, np.character, np.number)						):
           lowercase__				:     Dict					      =       data_struct.__array__()
       # support for nested types like struct of list of struct
       if isinstance(lowercase_			,		np.ndarray						):
           if data_struct.dtype == object:
               return self._consolidate([self.recursive_tensorize(lowercase_						) for substruct in data_struct]						)
       if isinstance(lowercase_			,		(list, tuple)						):
           return self._consolidate([self.recursive_tensorize(lowercase_						) for substruct in data_struct]						)
       return self._tensorize(lowercase_						)






   def    __UpperCamelCase  (   self       :  str			,		lowercase_       :  dict						)      ->		Dict:
       return map_nested(self._recursive_tensorize			,		lowercase_			,		map_list=lowercase_						)






   def    __UpperCamelCase  (   self       :  Any			,		lowercase_       :  pa.Table						)      ->		Mapping:
       lowercase__				:     Optional[Any]					      =       self.numpy_arrow_extractor().extract_row(lowercase_						)
       lowercase__				:     Dict					      =       self.python_features_decoder.decode_row(lowercase_						)
       return self.recursive_tensorize(lowercase_						)






   def    __UpperCamelCase  (   self       :  List[Any]			,		lowercase_       :  pa.Table						)      ->		np.ndarray:
       lowercase__				:     Optional[int]					      =       self.numpy_arrow_extractor().extract_column(lowercase_						)
       lowercase__				:     Optional[Any]					      =       self.python_features_decoder.decode_column(lowercase_			,		pa_table.column_names[0]						)
       lowercase__				:     List[Any]					      =       self.recursive_tensorize(lowercase_						)
       lowercase__				:     Union[str, Any]					      =       self._consolidate(lowercase_						)
       return column







   def    __UpperCamelCase  (   self       :  int			,		lowercase_       :  pa.Table						)      ->		Mapping:
       lowercase__				:     Union[str, Any]					      =       self.numpy_arrow_extractor().extract_batch(lowercase_						)
       lowercase__				:     List[str]					      =       self.python_features_decoder.decode_batch(lowercase_						)
       lowercase__				:     int					      =       self.recursive_tensorize(lowercase_						)
       for column_name in batch:
           lowercase__				:     Any					      =       self._consolidate(batch[column_name]						)
       return batch




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


UpperCamelCase													=		logging.get_logger(__name__)

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



class 						snake_case_ (	__A ):
   __A			:	Optional[Any]        =       RetriBertConfig
   __A			:	str        =       None
   __A			:	Any        =       "retribert"






   def    __UpperCamelCase  (   self       :  Dict			,		lowercase_       :  List[Any]						)      ->		List[str]:
       if isinstance(lowercase_			,		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(lowercase_			,		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(lowercase_			,		nn.LayerNorm						):
           module.bias.data.zero_()
           module.weight.data.fill_(1.0						)



UpperCamelCase													=		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 						snake_case_ (	__A ):






   def __init__(   self       :  Dict			,		lowercase_       :  RetriBertConfig						)      ->		None:
       super().__init__(lowercase_						)
       lowercase__				:     str					      =       config.projection_dim

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

       lowercase__				:     Optional[Any]					      =       nn.CrossEntropyLoss(reduction="mean"						)

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






   def    __UpperCamelCase  (   self       :  Dict			,		lowercase_       :  str			,		lowercase_       :  Optional[int]			,		lowercase_       :  Tuple			,		lowercase_       :  Optional[int]=-1			,		)      ->		List[str]:
       # reproduces BERT forward pass with checkpointing
       if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
           return sent_encoder(lowercase_			,		attention_mask=lowercase_						)[1]
       else:
           # prepare implicit variables
           lowercase__				:     Union[str, Any]					      =       input_ids.device
           lowercase__				:     Union[str, Any]					      =       input_ids.size()
           lowercase__				:     int					      =       torch.zeros(lowercase_			,		dtype=torch.long			,		device=lowercase_						)
           lowercase__				:     List[Any]					      =       [None] * sent_encoder.config.num_hidden_layers
           lowercase__				:     torch.Tensor					      =       sent_encoder.get_extended_attention_mask(
               lowercase_			,		lowercase_						)

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

           # run embedding layer on everything at once
           lowercase__				:     Optional[int]					      =       sent_encoder.embeddings(
               input_ids=lowercase_			,		position_ids=lowercase_			,		token_type_ids=lowercase_			,		inputs_embeds=lowercase_						)
           # run encoding and pooling on one mini-batch at a time
           lowercase__				:     str					      =       []
           for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size						)						):
               lowercase__				:     int					      =       embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
               lowercase__				:     int					      =       extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
               lowercase__				:     int					      =       checkpoint.checkpoint(lowercase_			,		lowercase_			,		lowercase_						)
               pooled_output_list.append(lowercase_						)
           return torch.cat(lowercase_			,		dim=0						)






   def    __UpperCamelCase  (   self       :  Optional[Any]			,		lowercase_       :  Any			,		lowercase_       :  Any=None			,		lowercase_       :  Union[str, Any]=-1			,		)      ->		List[str]:
       lowercase__				:     Optional[Any]					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query			,		lowercase_			,		)
       return self.project_query(lowercase_						)






   def    __UpperCamelCase  (   self       :  Union[str, Any]			,		lowercase_       :  Optional[Any]			,		lowercase_       :  Union[str, Any]=None			,		lowercase_       :  Dict=-1			,		)      ->		Optional[int]:
       lowercase__				:     str					      =       self.embed_sentences_checkpointed(
           lowercase_			,		lowercase_			,		self.bert_query if self.bert_doc is None else self.bert_doc			,		lowercase_			,		)
       return self.project_doc(lowercase_						)







   def    __UpperCamelCase  (   self       :  str			,		lowercase_       :  torch.LongTensor			,		lowercase_       :  Optional[torch.FloatTensor]			,		lowercase_       :  torch.LongTensor			,		lowercase_       :  Optional[torch.FloatTensor]			,		lowercase_       :  int = -1			,		)      ->		torch.FloatTensor:
       lowercase__				:     Tuple					      =       input_ids_query.device
       lowercase__				:     str					      =       self.embed_questions(lowercase_			,		lowercase_			,		lowercase_						)
       lowercase__				:     Any					      =       self.embed_answers(lowercase_			,		lowercase_			,		lowercase_						)
       lowercase__				:     List[str]					      =       torch.mm(lowercase_			,		a_reps.t()						)
       lowercase__				:     Optional[int]					      =       self.ce_loss(lowercase_			,		torch.arange(compare_scores.shape[1]						).to(lowercase_						)						)
       lowercase__				:     str					      =       self.ce_loss(compare_scores.t()			,		torch.arange(compare_scores.shape[0]						).to(lowercase_						)						)
       lowercase__				:     Tuple					      =       (loss_qa + loss_aq) / 2
       return loss



