

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


UpperCAmelCase							=					logging.get_logger(__name__)

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


class 					lowerCAmelCase       ( A				):
       lowerCAmelCase_				=	RetriBertConfig
       lowerCAmelCase_				=	None
       lowerCAmelCase_				=	"retribert"







       def      snake_case				(							self     :	Tuple  , __lowercase     :	List[str] ):







            """simple docstring"""







            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 					lowerCAmelCase       ( A				):







       def __init__(							self     :	int  , __lowercase     :	RetriBertConfig ):







            """simple docstring"""







            super().__init__(__lowercase )
            __lowercase     						=config.projection_dim

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

            __lowercase     						=nn.CrossEntropyLoss(reduction='mean' )

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







       def      snake_case				(							self     :	Dict  , __lowercase     :	List[Any]  , __lowercase     :	Any  , __lowercase     :	Optional[int]  , __lowercase     :	str=-1  , ):







            """simple docstring"""







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

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

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







       def      snake_case				(							self     :	List[Any]  , __lowercase     :	Any  , __lowercase     :	Any=None  , __lowercase     :	Optional[int]=-1  , ):







            """simple docstring"""







            __lowercase     						=self.embed_sentences_checkpointed(
                __lowercase  , __lowercase  , self.bert_query  , __lowercase  , )
            return self.project_query(__lowercase )







       def      snake_case				(							self     :	Dict  , __lowercase     :	Tuple  , __lowercase     :	Optional[int]=None  , __lowercase     :	Any=-1  , ):







            """simple docstring"""







            __lowercase     						=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      snake_case				(							self     :	int  , __lowercase     :	torch.LongTensor  , __lowercase     :	Optional[torch.FloatTensor]  , __lowercase     :	torch.LongTensor  , __lowercase     :	Optional[torch.FloatTensor]  , __lowercase     :	int = -1  , ):







            """simple docstring"""







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





'''simple docstring'''

from .number_theory.prime_numbers import next_prime


class 					lowerCAmelCase       :







       def __init__(							self     :	int  , __lowercase     :	int  , __lowercase     :	int | None = None  , __lowercase     :	float | None = None  , ):







            """simple docstring"""







            __lowercase     						=size_table
            __lowercase     						=[None] * self.size_table
            __lowercase     						=0.7_5 if lim_charge is None else lim_charge
            __lowercase     						=1 if charge_factor is None else charge_factor
            __lowercase     						=[]
            __lowercase     						={}







       def      snake_case				(							self     :	Dict ):







            """simple docstring"""







            return self._keys







       def      snake_case				(							self     :	Optional[Any] ):







            """simple docstring"""







            return sum(1 for slot in self.values if slot is not None ) / (
                self.size_table * self.charge_factor
            )







       def      snake_case				(							self     :	int  , __lowercase     :	int ):







            """simple docstring"""







            return key % self.size_table







       def      snake_case				(							self     :	int  , __lowercase     :	Any ):







            """simple docstring"""







            print(f'''step {step_ord}''' )
            print(list(range(len(self.values ) ) ) )
            print(self.values )







       def      snake_case				(							self     :	int  , __lowercase     :	int ):







            """simple docstring"""







            __lowercase     						=1
            __lowercase     						=values
            for value in values:
                 self.insert_data(__lowercase )
                 self._step_by_step(__lowercase )
                 i += 1







       def      snake_case				(							self     :	List[str]  , __lowercase     :	Optional[int]  , __lowercase     :	List[str] ):







            """simple docstring"""







            __lowercase     						=data
            __lowercase     						=data







       def      snake_case				(							self     :	int  , __lowercase     :	Any  , __lowercase     :	Optional[Any]=None ):







            """simple docstring"""







            __lowercase     						=self.hash_function(key + 1 )

            while self.values[new_key] is not None and self.values[new_key] != key:
                 if self.values.count(__lowercase ) > 0:
                      __lowercase     						=self.hash_function(new_key + 1 )
                 else:
                      __lowercase     						=None
                      break

            return new_key







       def      snake_case				(							self     :	Any ):







            """simple docstring"""







            __lowercase     						=[value for value in self.values if value is not None]
            __lowercase     						=next_prime(self.size_table  , factor=2 )
            self._keys.clear()
            __lowercase     						=[None] * self.size_table  # hell's pointers D: don't DRY ;/
            for value in survivor_values:
                 self.insert_data(__lowercase )







       def      snake_case				(							self     :	Optional[Any]  , __lowercase     :	Any ):







            """simple docstring"""







            __lowercase     						=self.hash_function(__lowercase )

            if self.values[key] is None:
                 self._set_value(__lowercase  , __lowercase )

            elif self.values[key] == data:
                 pass

            else:
                 __lowercase     						=self._collision_resolution(__lowercase  , __lowercase )
                 if collision_resolution is not None:
                      self._set_value(__lowercase  , __lowercase )
                 else:
                      self.rehashing()
                      self.insert_data(__lowercase )


