



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 :				Dict							=logging.get_logger(__name__)

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


class    _lowercase (a_   ):
				'''simple docstring'''







				lowercase__     =    RetriBertConfig
				lowercase__     =    None
				lowercase__     =    """retribert"""

				def    _lowerCamelCase       (			self  ,			snake_case__     ):

									'''simple docstring'''


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




UpperCAmelCase :				Tuple							=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    _lowercase (a_   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__     ):

									'''simple docstring'''


									super().__init__(snake_case__     )
									UpperCamelCase_			= config.projection_dim

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

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

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

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
														return sent_encoder(snake_case__  ,			attention_mask=snake_case__     )[1]
									else:
														# prepare implicit variables
														UpperCamelCase_			= input_ids.device
														UpperCamelCase_			= input_ids.size()
														UpperCamelCase_			= torch.zeros(snake_case__  ,			dtype=torch.long  ,			device=snake_case__     )
														UpperCamelCase_			= [None] * sent_encoder.config.num_hidden_layers
														UpperCamelCase_			= sent_encoder.get_extended_attention_mask(
														    snake_case__  ,			snake_case__     )

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

														# run embedding layer on everything at once
														UpperCamelCase_			= sent_encoder.embeddings(
														    input_ids=snake_case__  ,			position_ids=snake_case__  ,			token_type_ids=snake_case__  ,			inputs_embeds=snake_case__     )
														# 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(snake_case__  ,			snake_case__  ,			snake_case__     )
																			pooled_output_list.append(snake_case__     )
														return torch.cat(snake_case__  ,			dim=0     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__=None  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.embed_sentences_checkpointed(
									    snake_case__  ,			snake_case__  ,			self.bert_query  ,			snake_case__  ,			)
									return self.project_query(snake_case__     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__=None  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.embed_sentences_checkpointed(
									    snake_case__  ,			snake_case__  ,			self.bert_query if self.bert_doc is None else self.bert_doc  ,			snake_case__  ,			)
									return self.project_doc(snake_case__     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__ = -1  ,			):

									'''simple docstring'''


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



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""image_processor""", """tokenizer"""]
 UpperCAmelCase				     =    """LayoutLMv2ImageProcessor"""
 UpperCAmelCase				     =    ("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")


 def __init__(    self		:			Any      ,    lowerCAmelCase__		:			Any=None      ,    lowerCAmelCase__		:			Optional[Any]=None      ,    **lowerCAmelCase__		:			int     )     ->   Union[str, Any]:
   UpperCAmelCase          =	None
   if "feature_extractor" in kwargs:
     warnings.warn(
         "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
         " instead."      ,    lowerCAmelCase__      ,    )
     UpperCAmelCase          =	kwargs.pop("feature_extractor"     )

   UpperCAmelCase          =	image_processor if image_processor is not None else feature_extractor
   if image_processor is None:
     raise ValueError("You need to specify an `image_processor`."     )
   if tokenizer is None:
     raise ValueError("You need to specify a `tokenizer`."     )

   super().__init__(lowerCAmelCase__      ,    lowerCAmelCase__     )


 def __call__(    self		:			int      ,    lowerCAmelCase__		:			Tuple      ,    lowerCAmelCase__		:			Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,    lowerCAmelCase__		:			Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None      ,    lowerCAmelCase__		:			Union[List[List[int]], List[List[List[int]]]] = None      ,    lowerCAmelCase__		:			Optional[Union[List[int], List[List[int]]]] = None      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Union[bool, str, PaddingStrategy] = False      ,    lowerCAmelCase__		:			Union[bool, str, TruncationStrategy] = False      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			int = 0      ,    lowerCAmelCase__		:			Optional[int] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			Optional[bool] = None      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = False      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Optional[Union[str, TensorType]] = None      ,    **lowerCAmelCase__		:			Any      ,    )     ->   BatchEncoding:
   # verify input
   if self.image_processor.apply_ocr and (boxes is not None):
     raise ValueError(
         "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."     )

   if self.image_processor.apply_ocr and (word_labels is not None):
     raise ValueError(
         "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."     )

   if return_overflowing_tokens is True and return_offsets_mapping is False:
     raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."     )

   # first, apply the image processor
   UpperCAmelCase          =	self.image_processor(images=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__     )

   # second, apply the tokenizer
   if text is not None and self.image_processor.apply_ocr and text_pair is None:
     if isinstance(lowerCAmelCase__      ,    lowerCAmelCase__     ):
       UpperCAmelCase          =	[text]  # add batch dimension (as the image processor always adds a batch dimension)
     UpperCAmelCase          =	features["words"]

   UpperCAmelCase          =	self.tokenizer(
       text=text if text is not None else features["words"]      ,    text_pair=text_pair if text_pair is not None else None      ,    boxes=boxes if boxes is not None else features["boxes"]      ,    word_labels=lowerCAmelCase__      ,    add_special_tokens=lowerCAmelCase__      ,    padding=lowerCAmelCase__      ,    truncation=lowerCAmelCase__      ,    max_length=lowerCAmelCase__      ,    stride=lowerCAmelCase__      ,    pad_to_multiple_of=lowerCAmelCase__      ,    return_token_type_ids=lowerCAmelCase__      ,    return_attention_mask=lowerCAmelCase__      ,    return_overflowing_tokens=lowerCAmelCase__      ,    return_special_tokens_mask=lowerCAmelCase__      ,    return_offsets_mapping=lowerCAmelCase__      ,    return_length=lowerCAmelCase__      ,    verbose=lowerCAmelCase__      ,    return_tensors=lowerCAmelCase__      ,    **lowerCAmelCase__      ,    )

   # add pixel values
   UpperCAmelCase          =	features.pop("pixel_values"     )
   if return_overflowing_tokens is True:
     UpperCAmelCase          =	self.get_overflowing_images(lowerCAmelCase__      ,    encoded_inputs["overflow_to_sample_mapping"]     )
   UpperCAmelCase          =	images

   return encoded_inputs


 def _UpperCamelCase						(    self		:			str      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Union[str, Any]     )     ->   int:
   # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
   UpperCAmelCase          =	[]
   for sample_idx in overflow_to_sample_mapping:
     images_with_overflow.append(images[sample_idx]     )

   if len(lowerCAmelCase__     ) != len(lowerCAmelCase__     ):
     raise ValueError(
         "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
         f" {len(lowerCAmelCase__     )} and {len(lowerCAmelCase__     )}"     )

   return images_with_overflow


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    *lowerCAmelCase__		:			int      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[str]:
   return self.tokenizer.batch_decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    *lowerCAmelCase__		:			Tuple      ,    **lowerCAmelCase__		:			Union[str, Any]     )     ->   List[Any]:
   return self.tokenizer.decode(*lowerCAmelCase__      ,    **lowerCAmelCase__     )


 @property
 def _UpperCamelCase						(    self		:			int     )     ->   List[str]:
   return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]


 @property
 def _UpperCamelCase						(    self		:			Dict     )     ->   List[str]:
   warnings.warn(
       "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor_class


 @property
 def _UpperCamelCase						(    self		:			List[Any]     )     ->   int:
   warnings.warn(
       "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."      ,    lowerCAmelCase__      ,    )
   return self.image_processor



