




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


_lowerCamelCase					:     str					  =  logging.get_logger(__name__)

_lowerCamelCase					:     Optional[int]					  =  [
    "yjernite/retribert-base-uncased",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]
class 				__snake_case     (_a						):
				lowerCAmelCase__			=   RetriBertConfig
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   "retribert"



				def 					SCREAMING_SNAKE_CASE				(					self					:						Tuple						,		_UpperCAmelCase					:						Dict					)     ->			List[Any]:





								'''simple docstring'''




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






_lowerCamelCase					:     str					  =  R"\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"
@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."  ,		_a  ,		)
class 				__snake_case     (_a						):



				def __init__(					self					:						int						,		_UpperCAmelCase					:						RetriBertConfig					)     ->			None:





								'''simple docstring'''




								super().__init__(_UpperCAmelCase					)
								_lowerCAmelCase			:			str        =					config.projection_dim

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

								_lowerCAmelCase			:			List[Any]        =					nn.CrossEntropyLoss(reduction="""mean"""					)

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



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





								'''simple docstring'''




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

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

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



				def 					SCREAMING_SNAKE_CASE				(					self					:						Union[str, Any]						,		_UpperCAmelCase					:						Union[str, Any]						,		_UpperCAmelCase					:						Tuple=None						,		_UpperCAmelCase					:						Any=-1						,		)     ->			Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Any        =					self.embed_sentences_checkpointed(
								    _UpperCAmelCase						,		_UpperCAmelCase						,		self.bert_query						,		_UpperCAmelCase						,		)
								return self.project_query(_UpperCAmelCase					)



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





								'''simple docstring'''




								_lowerCAmelCase			:			Optional[int]        =					self.embed_sentences_checkpointed(
								    _UpperCAmelCase						,		_UpperCAmelCase						,		self.bert_query if self.bert_doc is None else self.bert_doc						,		_UpperCAmelCase						,		)
								return self.project_doc(_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Dict						,		_UpperCAmelCase					:						torch.LongTensor						,		_UpperCAmelCase					:						Optional[torch.FloatTensor]						,		_UpperCAmelCase					:						torch.LongTensor						,		_UpperCAmelCase					:						Optional[torch.FloatTensor]						,		_UpperCAmelCase					:						int = -1						,		)     ->			torch.FloatTensor:





								'''simple docstring'''




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





import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
   from .testing_utils import (
       floats_tensor,
       load_hf_numpy,
       load_image,
       load_numpy,
       load_pt,
       nightly,
       parse_flag_from_env,
       print_tensor_test,
       require_torch_a,
       require_torch_gpu,
       skip_mps,
       slow,
       torch_all_close,
       torch_device,
   )
   from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


UpperCAmelCase			=    get_logger(__name__)






def        __lowerCAmelCase    (SCREAMING_SNAKE_CASE					)->  Tuple:




      """simple docstring"""

      if version.parse(SCREAMING_SNAKE_CASE					) < version.parse(SCREAMING_SNAKE_CASE					):
            if "dev" in min_version:
                  snake_case_       =      (
                      '''This example requires a source install from HuggingFace diffusers (see '''
                      '''`https://huggingface.co/docs/diffusers/installation#install-from-source`),'''
                  )
            else:
                  snake_case_       =      f'''This example requires a minimum version of {min_version},'''
            error_message += f''' but the version found is {__version__}.\n'''
            raise ImportError(SCREAMING_SNAKE_CASE					)