
"""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_			      =					logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_			      =					[
    '''yjernite/retribert-base-uncased''',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]
class      lowerCAmelCase_						(							A__				):



							'''simple docstring'''





							_snake_case		     =						RetriBertConfig
							_snake_case		     =						None
							_snake_case		     =						'''retribert'''




							def  A__		(				self  ,							snake_case_							)   ->       Optional[Any]:
													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							)
SCREAMING_SNAKE_CASE_			      =					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__				):



							'''simple docstring'''





							def __init__(				self  ,							snake_case_							)   ->       None:
													super().__init__(snake_case_							)
													__lowerCAmelCase        =       config.projection_dim

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

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

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




							def  A__		(				self  ,							snake_case_  ,							snake_case_  ,							snake_case_  ,							snake_case_=-1  ,							)   ->       Tuple:
													# reproduces BERT forward pass with checkpointing
													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
																			__lowerCAmelCase        =       input_ids.device
																			__lowerCAmelCase        =       input_ids.size()
																			__lowerCAmelCase        =       torch.zeros(snake_case_  ,							dtype=torch.long  ,							device=snake_case_							)
																			__lowerCAmelCase        =       [None] * sent_encoder.config.num_hidden_layers
																			__lowerCAmelCase        =       sent_encoder.get_extended_attention_mask(
																			    snake_case_  ,							snake_case_							)

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

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




							def  A__		(				self  ,							snake_case_  ,							snake_case_=None  ,							snake_case_=-1  ,							)   ->       List[Any]:
													__lowerCAmelCase        =       self.embed_sentences_checkpointed(
													    snake_case_  ,							snake_case_  ,							self.bert_query  ,							snake_case_  ,							)
													return self.project_query(snake_case_							)




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


"""simple docstring"""
import unittest

from transformers import is_torch_available, load_tool

from .test_tools_common import ToolTesterMixin


if is_torch_available():
			import torch
class      lowerCAmelCase_						(							unittest.TestCase							,							A__				):



							'''simple docstring'''





							def  A__		(				self							)   ->       Any:
													__lowerCAmelCase        =       load_tool("""speech-to-text"""							)
													self.tool.setup()




							def  A__		(				self							)   ->       int:
													__lowerCAmelCase        =       self.tool(torch.ones(3_000							)							)
													self.assertEqual(snake_case_  ,							""" you"""							)




							def  A__		(				self							)   ->       Optional[int]:
													__lowerCAmelCase        =       self.tool(audio=torch.ones(3_000							)							)
													self.assertEqual(snake_case_  ,							""" you"""							)
