





'''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__							:							List[str]			=logging.get_logger(__name__)

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

class 					snake_case					(   __lowerCamelCase	):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_     : Optional[int]      		=RetriBertConfig
 SCREAMING_SNAKE_CASE_     : Tuple      		=None
 SCREAMING_SNAKE_CASE_     : int      		="retribert"






 def 	_lowerCamelCase (	self	:							Optional[Any]							,     __A	:							Tuple     ):
        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     )






a__							:							List[str]			=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."      ,	__lowerCamelCase      ,	)
class 					snake_case					(   __lowerCamelCase	):




 """simple docstring"""



 def __init__(	self	:							int							,     __A	:							RetriBertConfig     ):
        super().__init__(__A     )
        __UpperCamelCase	=  config.projection_dim

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

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

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






 def 	_lowerCamelCase (	self	:							str							,     __A	:							List[str]							,     __A	:							Union[str, Any]							,     __A	:							Dict							,     __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	=  input_ids.device
               __UpperCamelCase	=  input_ids.size()
               __UpperCamelCase	=  torch.zeros(__A							,     dtype=torch.long							,     device=__A     )
               __UpperCamelCase	=  [None] * sent_encoder.config.num_hidden_layers
               __UpperCamelCase	=  sent_encoder.get_extended_attention_mask(
                   __A							,     __A     )

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

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






 def 	_lowerCamelCase (	self	:							Union[str, Any]							,     __A	:							str							,     __A	:							List[Any]=None							,     __A	:							List[Any]=-1							,     ):
        __UpperCamelCase	=  self.embed_sentences_checkpointed(
            __A							,     __A							,     self.bert_query							,     __A							,     )
        return self.project_query(__A     )






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







'''simple docstring'''
import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
    from .tokenization_mbartaa import MBartaaTokenizer
else:
    a__							:							Union[str, Any]			=None


a__							:							str			=logging.get_logger(__name__)

a__							:							Optional[Any]			={'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}

a__							:							List[Any]			={
    '''vocab_file''': {
        '''facebook/mbart-large-50-one-to-many-mmt''': (
            '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/mbart-large-50-one-to-many-mmt''': (
            '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/tokenizer.json'''
        ),
    },
}

a__							:							List[Any]			={
    '''facebook/mbart-large-50-one-to-many-mmt''': 1_024,
}

# fmt: off
a__							:							int			=['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''', '''af_ZA''', '''az_AZ''', '''bn_IN''', '''fa_IR''', '''he_IL''', '''hr_HR''', '''id_ID''', '''ka_GE''', '''km_KH''', '''mk_MK''', '''ml_IN''', '''mn_MN''', '''mr_IN''', '''pl_PL''', '''ps_AF''', '''pt_XX''', '''sv_SE''', '''sw_KE''', '''ta_IN''', '''te_IN''', '''th_TH''', '''tl_XX''', '''uk_UA''', '''ur_PK''', '''xh_ZA''', '''gl_ES''', '''sl_SI''']

class 					snake_case					(   __lowerCamelCase	):




 """simple docstring"""



 SCREAMING_SNAKE_CASE_     : Any      		=VOCAB_FILES_NAMES
 SCREAMING_SNAKE_CASE_     : Dict      		=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 SCREAMING_SNAKE_CASE_     : List[str]      		=PRETRAINED_VOCAB_FILES_MAP
 SCREAMING_SNAKE_CASE_     : Any      		=["input_ids", "attention_mask"]
 SCREAMING_SNAKE_CASE_     : Dict      		=MBartaaTokenizer

 SCREAMING_SNAKE_CASE_     : List[int]      		=[]
 SCREAMING_SNAKE_CASE_     : List[int]      		=[]






 def __init__(	self	:							Any							,     __A	:							Union[str, Any]=None							,     __A	:							Tuple=None							,     __A	:							Optional[int]=None							,     __A	:							List[Any]=None							,     __A	:							Optional[Any]="</s>"							,     __A	:							Any="</s>"							,     __A	:							Optional[Any]="<s>"							,     __A	:							List[Any]="<unk>"							,     __A	:							Tuple="<pad>"							,     __A	:							Union[str, Any]="<mask>"							,     **__A	:							Any							,     ):
        # Mask token behave like a normal word, i.e. include the space before it
        __UpperCamelCase	=  AddedToken(__A							,     lstrip=__A							,     rstrip=__A     ) if isinstance(__A							,     __A     ) else mask_token

        __UpperCamelCase	=  kwargs.get('additional_special_tokens'							,     []     )
        kwargs["additional_special_tokens"] += [
            code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
        ]

        super().__init__(
            __A							,     src_lang=__A							,     tgt_lang=__A							,     tokenizer_file=__A							,     eos_token=__A							,     sep_token=__A							,     cls_token=__A							,     unk_token=__A							,     pad_token=__A							,     mask_token=__A							,     **__A							,     )

        __UpperCamelCase	=  vocab_file
        __UpperCamelCase	=  False if not self.vocab_file else True

        __UpperCamelCase	=  {
            lang_code: self.convert_tokens_to_ids(__A     ) for lang_code in FAIRSEQ_LANGUAGE_CODES
        }

        __UpperCamelCase	=  src_lang if src_lang is not None else 'en_XX'
        __UpperCamelCase	=  tgt_lang
        __UpperCamelCase	=  self.lang_code_to_id[self._src_lang]
        self.set_src_lang_special_tokens(self._src_lang     )






 @property
 def 	_lowerCamelCase (	self	:							Tuple     ):
        return self._src_lang






 @src_lang.setter
 def 	_lowerCamelCase (	self	:							Optional[int]							,     __A	:							str     ):
        __UpperCamelCase	=  new_src_lang
        self.set_src_lang_special_tokens(self._src_lang     )






 def 	_lowerCamelCase (	self	:							Optional[int]							,     __A	:							List[int]							,     __A	:							Optional[List[int]] = None     ):
        if token_ids_a is None:
               return self.prefix_tokens + token_ids_a + self.suffix_tokens
        # We don't expect to process pairs, but leave the pair logic for API consistency
        return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens






 def 	_lowerCamelCase (	self	:							List[Any]							,     __A	:							List[str]							,     __A	:							str = "en_XX"							,     __A	:							Optional[List[str]] = None							,     __A	:							str = "ro_RO"							,     **__A	:							Optional[int]							,     ):
        __UpperCamelCase	=  src_lang
        __UpperCamelCase	=  tgt_lang
        return super().prepare_seqaseq_batch(__A							,     __A							,     **__A     )






 def 	_lowerCamelCase (	self	:							List[str]     ):
        return self.set_src_lang_special_tokens(self.src_lang     )






 def 	_lowerCamelCase (	self	:							List[str]     ):
        return self.set_tgt_lang_special_tokens(self.tgt_lang     )






 def 	_lowerCamelCase (	self	:							Optional[int]							,     __A	:							str     ):
        __UpperCamelCase	=  self.convert_tokens_to_ids(__A     )
        __UpperCamelCase	=  [self.cur_lang_code_id]
        __UpperCamelCase	=  [self.eos_token_id]

        __UpperCamelCase	=  self.convert_ids_to_tokens(self.prefix_tokens     )
        __UpperCamelCase	=  self.convert_ids_to_tokens(self.suffix_tokens     )

        __UpperCamelCase	=  processors.TemplateProcessing(
            single=prefix_tokens_str + ['$A'] + suffix_tokens_str							,     pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str							,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,     self.prefix_tokens + self.suffix_tokens     )     )							,     )






 def 	_lowerCamelCase (	self	:							Union[str, Any]							,     __A	:							str     ):
        __UpperCamelCase	=  self.convert_tokens_to_ids(__A     )
        __UpperCamelCase	=  [self.cur_lang_code_id]
        __UpperCamelCase	=  [self.eos_token_id]

        __UpperCamelCase	=  self.convert_ids_to_tokens(self.prefix_tokens     )
        __UpperCamelCase	=  self.convert_ids_to_tokens(self.suffix_tokens     )

        __UpperCamelCase	=  processors.TemplateProcessing(
            single=prefix_tokens_str + ['$A'] + suffix_tokens_str							,     pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str							,     special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str							,     self.prefix_tokens + self.suffix_tokens     )     )							,     )






 def 	_lowerCamelCase (	self	:							str							,     __A	:							Union[str, Any]							,     __A	:							str							,     __A	:							Optional[str]							,     __A	:							Optional[str]							,     **__A	:							Dict     ):
        if src_lang is None or tgt_lang is None:
               raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model'     )
        __UpperCamelCase	=  src_lang
        __UpperCamelCase	=  self(__A							,     add_special_tokens=__A							,     return_tensors=__A							,     **__A     )
        __UpperCamelCase	=  self.convert_tokens_to_ids(__A     )
        __UpperCamelCase	=  tgt_lang_id
        return inputs






 def 	_lowerCamelCase (	self	:							List[str]							,     __A	:							str							,     __A	:							Optional[str] = None     ):
        if not self.can_save_slow_tokenizer:
               raise ValueError(
                   'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '
                   'tokenizer.'     )

        if not os.path.isdir(__A     ):
               logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''     )
               return
        __UpperCamelCase	=  os.path.join(
            __A							,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']     )

        if os.path.abspath(self.vocab_file     ) != os.path.abspath(__A     ):
               copyfile(self.vocab_file							,     __A     )

        return (out_vocab_file,)
