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

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



class 			UpperCamelCase_			(						lowerCAmelCase__   ):




							'''simple docstring'''

							UpperCamelCase_					   =							RetriBertConfig
							UpperCamelCase_					   =							None
							UpperCamelCase_					   =							"""retribert"""
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase) ->	Optional[int]:

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

UpperCAmelCase__				:  List[Any]       					=				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 			UpperCamelCase_			(						lowerCAmelCase__   ):




							'''simple docstring'''

							def __init__(				self     ,						UpperCamelCase) ->	str:
										super().__init__(_lowerCamelCase)
										UpperCamelCase__    :		Dict     =				config.projection_dim

										UpperCamelCase__    :		Optional[Any]     =				BertModel(_lowerCamelCase)
										UpperCamelCase__    :		Optional[int]     =				None if config.share_encoders else BertModel(_lowerCamelCase)
										UpperCamelCase__    :		Optional[int]     =				nn.Dropout(config.hidden_dropout_prob)
										UpperCamelCase__    :		Dict     =				nn.Linear(config.hidden_size     ,						config.projection_dim     ,						bias=_lowerCamelCase)
										UpperCamelCase__    :		Tuple     =				nn.Linear(config.hidden_size     ,						config.projection_dim     ,						bias=_lowerCamelCase)

										UpperCamelCase__    :		Optional[Any]     =				nn.CrossEntropyLoss(reduction='mean')

										# Initialize weights and apply final processing
										self.post_init()
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase=-1     ,						) ->	Optional[int]:

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

													# define function for checkpointing
													def partial_encode(*UpperCamelCase):
																UpperCamelCase__    :		Optional[int]     =				sent_encoder.encoder(
																    inputs[0]     ,						attention_mask=inputs[1]     ,						head_mask=_lowerCamelCase     ,						)
																UpperCamelCase__    :		Any     =				encoder_outputs[0]
																UpperCamelCase__    :		int     =				sent_encoder.pooler(_lowerCamelCase)
																return pooled_output

													# run embedding layer on everything at once
													UpperCamelCase__    :		Optional[Any]     =				sent_encoder.embeddings(
													    input_ids=_lowerCamelCase     ,						position_ids=_lowerCamelCase     ,						token_type_ids=_lowerCamelCase     ,						inputs_embeds=_lowerCamelCase)
													# run encoding and pooling on one mini-batch at a time
													UpperCamelCase__    :		Union[str, Any]     =				[]
													for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
																UpperCamelCase__    :		List[str]     =				embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																UpperCamelCase__    :		Dict     =				extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																UpperCamelCase__    :		List[str]     =				checkpoint.checkpoint(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase)
																pooled_output_list.append(_lowerCamelCase)
													return torch.cat(_lowerCamelCase     ,						dim=0)
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase=None     ,						UpperCamelCase=-1     ,						) ->	Optional[int]:
										UpperCamelCase__    :		Dict     =				self.embed_sentences_checkpointed(
										    _lowerCamelCase     ,						_lowerCamelCase     ,						self.bert_query     ,						_lowerCamelCase     ,						)
										return self.project_query(_lowerCamelCase)
							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase=None     ,						UpperCamelCase=-1     ,						) ->	Optional[int]:
										UpperCamelCase__    :		Optional[int]     =				self.embed_sentences_checkpointed(
										    _lowerCamelCase     ,						_lowerCamelCase     ,						self.bert_query if self.bert_doc is None else self.bert_doc     ,						_lowerCamelCase     ,						)
										return self.project_doc(_lowerCamelCase)






							def        lowerCAmelCase__ (				self     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase     ,						UpperCamelCase = -1     ,						) ->	List[Any]:
										UpperCamelCase__    :		Optional[Any]     =				input_ids_query.device
										UpperCamelCase__    :		str     =				self.embed_questions(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase)
										UpperCamelCase__    :		Union[str, Any]     =				self.embed_answers(_lowerCamelCase     ,						_lowerCamelCase     ,						_lowerCamelCase)
										UpperCamelCase__    :		Any     =				torch.mm(_lowerCamelCase     ,						a_reps.t())
										UpperCamelCase__    :		Any     =				self.ce_loss(_lowerCamelCase     ,						torch.arange(compare_scores.shape[1]).to(_lowerCamelCase))
										UpperCamelCase__    :		List[str]     =				self.ce_loss(compare_scores.t()     ,						torch.arange(compare_scores.shape[0]).to(_lowerCamelCase))
										UpperCamelCase__    :		str     =				(loss_qa + loss_aq) / 2
										return loss





from typing import Optional

from ..utils.logging import get_logger
from .audio_classificiation import AudioClassification
from .automatic_speech_recognition import AutomaticSpeechRecognition
from .base import TaskTemplate
from .image_classification import ImageClassification
from .language_modeling import LanguageModeling
from .question_answering import QuestionAnsweringExtractive
from .summarization import Summarization
from .text_classification import TextClassification


UpperCAmelCase__				:  Tuple       					=				[
    '''AutomaticSpeechRecognition''',
    '''AudioClassification''',
    '''ImageClassification''',
    '''LanguageModeling''',
    '''QuestionAnsweringExtractive''',
    '''Summarization''',
    '''TaskTemplate''',
    '''TextClassification''',
]

UpperCAmelCase__				:  Dict       					=				get_logger(__name__)


UpperCAmelCase__				:  Dict       					=				{
    AutomaticSpeechRecognition.task: AutomaticSpeechRecognition,
    AudioClassification.task: AudioClassification,
    ImageClassification.task: ImageClassification,
    LanguageModeling.task: LanguageModeling,
    QuestionAnsweringExtractive.task: QuestionAnsweringExtractive,
    Summarization.task: Summarization,
    TextClassification.task: TextClassification,
}



def       _lowercase					(      __SCREAMING_SNAKE_CASE )	->     Optional[TaskTemplate]:
			UpperCamelCase__    :		Any     =				task_template_dict.get('task' )
			if task_name is None:
						logger.warning(F"""Couldn't find template for task '{task_name}'. Available templates: {list(__SCREAMING_SNAKE_CASE )}""" )
						return None
			UpperCamelCase__    :		Any     =				NAMEaTEMPLATE.get(__SCREAMING_SNAKE_CASE )
			return template.from_dict(__SCREAMING_SNAKE_CASE )



