



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


SCREAMING_SNAKE_CASE__     : Optional[int]				=   logging.get_logger(__name__)

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




class 				__lowerCAmelCase(							lowerCAmelCase__      ):
			__snake_case  :		Dict		=      RetriBertConfig
			__snake_case  :		List[Any]		=      None
			__snake_case  :		Union[str, Any]		=      'retribert'






			def 				_lowercase	(   self  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							List[Any]	):




					"""simple docstring"""







					if isinstance(SCREAMING_SNAKE_CASE      ,       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(SCREAMING_SNAKE_CASE      ,       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(SCREAMING_SNAKE_CASE      ,       nn.LayerNorm	):
							module.bias.data.zero_()
							module.weight.data.fill_(1.0	)


SCREAMING_SNAKE_CASE__     : 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 				__lowerCAmelCase(							lowerCAmelCase__      ):






			def __init__(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							RetriBertConfig	):




					"""simple docstring"""







					super().__init__(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Any										=      config.projection_dim

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

					SCREAMING_SNAKE_CASE_						:int										=      nn.CrossEntropyLoss(reduction='mean'	)

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






			def 				_lowercase	(   self  :							Dict      ,       SCREAMING_SNAKE_CASE  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							str      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							Tuple=-1      ,       ):




					"""simple docstring"""







					if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
							return sent_encoder(SCREAMING_SNAKE_CASE      ,       attention_mask=SCREAMING_SNAKE_CASE	)[1]
					else:
							# prepare implicit variables
							SCREAMING_SNAKE_CASE_						:Tuple										=      input_ids.device
							SCREAMING_SNAKE_CASE_						:Any										=      input_ids.size()
							SCREAMING_SNAKE_CASE_						:Any										=      torch.zeros(SCREAMING_SNAKE_CASE      ,       dtype=torch.long      ,       device=SCREAMING_SNAKE_CASE	)
							SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      [None] * sent_encoder.config.num_hidden_layers
							SCREAMING_SNAKE_CASE_						:torch.Tensor										=      sent_encoder.get_extended_attention_mask(
							    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)

							# define function for checkpointing
							def partial_encode(*SCREAMING_SNAKE_CASE  :							Union[str, Any]	):
									SCREAMING_SNAKE_CASE_						:List[Any]										=      sent_encoder.encoder(
									    inputs[0]      ,       attention_mask=inputs[1]      ,       head_mask=SCREAMING_SNAKE_CASE      ,       )
									SCREAMING_SNAKE_CASE_						:int										=      encoder_outputs[0]
									SCREAMING_SNAKE_CASE_						:Optional[Any]										=      sent_encoder.pooler(SCREAMING_SNAKE_CASE	)
									return pooled_output

							# run embedding layer on everything at once
							SCREAMING_SNAKE_CASE_						:Dict										=      sent_encoder.embeddings(
							    input_ids=SCREAMING_SNAKE_CASE      ,       position_ids=SCREAMING_SNAKE_CASE      ,       token_type_ids=SCREAMING_SNAKE_CASE      ,       inputs_embeds=SCREAMING_SNAKE_CASE	)
							# run encoding and pooling on one mini-batch at a time
							SCREAMING_SNAKE_CASE_						:str										=      []
							for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size	)	):
									SCREAMING_SNAKE_CASE_						:Optional[int]										=      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(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
									pooled_output_list.append(SCREAMING_SNAKE_CASE	)
							return torch.cat(SCREAMING_SNAKE_CASE      ,       dim=0	)






			def 				_lowercase	(   self  :							Optional[Any]      ,       SCREAMING_SNAKE_CASE  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							Any=None      ,       SCREAMING_SNAKE_CASE  :							str=-1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Dict										=      self.embed_sentences_checkpointed(
					    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       self.bert_query      ,       SCREAMING_SNAKE_CASE      ,       )
					return self.project_query(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							str      ,       SCREAMING_SNAKE_CASE  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							List[str]=None      ,       SCREAMING_SNAKE_CASE  :							int=-1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:int										=      self.embed_sentences_checkpointed(
					    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       self.bert_query if self.bert_doc is None else self.bert_doc      ,       SCREAMING_SNAKE_CASE      ,       )
					return self.project_doc(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							torch.LongTensor      ,       SCREAMING_SNAKE_CASE  :							Optional[torch.FloatTensor]      ,       SCREAMING_SNAKE_CASE  :							torch.LongTensor      ,       SCREAMING_SNAKE_CASE  :							Optional[torch.FloatTensor]      ,       SCREAMING_SNAKE_CASE  :							int = -1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      input_ids_query.device
					SCREAMING_SNAKE_CASE_						:Any										=      self.embed_questions(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      self.embed_answers(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Dict										=      torch.mm(SCREAMING_SNAKE_CASE      ,       a_reps.t()	)
					SCREAMING_SNAKE_CASE_						:str										=      self.ce_loss(SCREAMING_SNAKE_CASE      ,       torch.arange(compare_scores.shape[1]	).to(SCREAMING_SNAKE_CASE	)	)
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      self.ce_loss(compare_scores.t()      ,       torch.arange(compare_scores.shape[0]	).to(SCREAMING_SNAKE_CASE	)	)
					SCREAMING_SNAKE_CASE_						:Optional[int]										=      (loss_qa + loss_aq) / 2
					return loss





'''simple docstring'''







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_layoutlm import LayoutLMTokenizer


SCREAMING_SNAKE_CASE__     : List[Any]				=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__     : List[str]				=   {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

SCREAMING_SNAKE_CASE__     : Optional[int]				=   {
    """vocab_file""": {
        """microsoft/layoutlm-base-uncased""": (
            """https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/vocab.txt"""
        ),
        """microsoft/layoutlm-large-uncased""": (
            """https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """microsoft/layoutlm-base-uncased""": (
            """https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/tokenizer.json"""
        ),
        """microsoft/layoutlm-large-uncased""": (
            """https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/tokenizer.json"""
        ),
    },
}

SCREAMING_SNAKE_CASE__     : Tuple				=   {
    """microsoft/layoutlm-base-uncased""": 5_12,
    """microsoft/layoutlm-large-uncased""": 5_12,
}

SCREAMING_SNAKE_CASE__     : List[Any]				=   {
    """microsoft/layoutlm-base-uncased""": {"""do_lower_case""": True},
    """microsoft/layoutlm-large-uncased""": {"""do_lower_case""": True},
}




class 				__lowerCAmelCase(							lowerCAmelCase__      ):
			__snake_case  :		List[str]		=      VOCAB_FILES_NAMES
			__snake_case  :		Dict		=      PRETRAINED_VOCAB_FILES_MAP
			__snake_case  :		Optional[int]		=      PRETRAINED_INIT_CONFIGURATION
			__snake_case  :		Any		=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__snake_case  :		str		=      LayoutLMTokenizer






			def __init__(   self  :							Optional[int]      ,       SCREAMING_SNAKE_CASE  :							Dict=None      ,       SCREAMING_SNAKE_CASE  :							int=None      ,       SCREAMING_SNAKE_CASE  :							Tuple=True      ,       SCREAMING_SNAKE_CASE  :							Optional[int]="[UNK]"      ,       SCREAMING_SNAKE_CASE  :							Tuple="[SEP]"      ,       SCREAMING_SNAKE_CASE  :							int="[PAD]"      ,       SCREAMING_SNAKE_CASE  :							List[Any]="[CLS]"      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]="[MASK]"      ,       SCREAMING_SNAKE_CASE  :							Optional[Any]=True      ,       SCREAMING_SNAKE_CASE  :							Union[str, Any]=None      ,       **SCREAMING_SNAKE_CASE  :							Optional[int]      ,       ):




					"""simple docstring"""







					super().__init__(
					    SCREAMING_SNAKE_CASE      ,       tokenizer_file=SCREAMING_SNAKE_CASE      ,       do_lower_case=SCREAMING_SNAKE_CASE      ,       unk_token=SCREAMING_SNAKE_CASE      ,       sep_token=SCREAMING_SNAKE_CASE      ,       pad_token=SCREAMING_SNAKE_CASE      ,       cls_token=SCREAMING_SNAKE_CASE      ,       mask_token=SCREAMING_SNAKE_CASE      ,       tokenize_chinese_chars=SCREAMING_SNAKE_CASE      ,       strip_accents=SCREAMING_SNAKE_CASE      ,       **SCREAMING_SNAKE_CASE      ,       )

					SCREAMING_SNAKE_CASE_						:str										=      json.loads(self.backend_tokenizer.normalizer.__getstate__()	)
					if (
					    normalizer_state.get('lowercase'      ,       SCREAMING_SNAKE_CASE	) != do_lower_case
					    or normalizer_state.get('strip_accents'      ,       SCREAMING_SNAKE_CASE	) != strip_accents
					    or normalizer_state.get('handle_chinese_chars'      ,       SCREAMING_SNAKE_CASE	) != tokenize_chinese_chars
					):
							SCREAMING_SNAKE_CASE_						:List[str]										=      getattr(SCREAMING_SNAKE_CASE      ,       normalizer_state.pop('type'	)	)
							SCREAMING_SNAKE_CASE_						:Tuple										=      do_lower_case
							SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      strip_accents
							SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      tokenize_chinese_chars
							SCREAMING_SNAKE_CASE_						:Optional[int]										=      normalizer_class(**SCREAMING_SNAKE_CASE	)

					SCREAMING_SNAKE_CASE_						:List[str]										=      do_lower_case






			def 				_lowercase	(   self  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							Optional[int]      ,       SCREAMING_SNAKE_CASE  :							str=None	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[int]										=      [self.cls_token_id] + token_ids_a + [self.sep_token_id]

					if token_ids_a:
							output += token_ids_a + [self.sep_token_id]

					return output






			def 				_lowercase	(   self  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							List[int]      ,       SCREAMING_SNAKE_CASE  :							Optional[List[int]] = None	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      [self.sep_token_id]
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      [self.cls_token_id]
					if token_ids_a is None:
							return len(cls + token_ids_a + sep	) * [0]
					return len(cls + token_ids_a + sep	) * [0] + len(token_ids_a + sep	) * [1]






			def 				_lowercase	(   self  :							str      ,       SCREAMING_SNAKE_CASE  :							str      ,       SCREAMING_SNAKE_CASE  :							Optional[str] = None	):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Tuple										=      self._tokenizer.model.save(SCREAMING_SNAKE_CASE      ,       name=SCREAMING_SNAKE_CASE	)
					return tuple(SCREAMING_SNAKE_CASE	)
