

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

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





class      snake_case_      (					__UpperCamelCase				):


							"""simple docstring"""





							__UpperCAmelCase      =RetriBertConfig
							__UpperCAmelCase      =None
							__UpperCAmelCase      ="retribert"




							def 							A__	(			self       ,    _A				):
												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				)
lowerCamelCase   					=  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."""      ,			__UpperCamelCase      ,			)
class      snake_case_      (					__UpperCamelCase				):


							"""simple docstring"""





							def __init__(			self       ,    _A				):
												super().__init__(_lowerCAmelCase				)
												__lowerCAmelCase       =				config.projection_dim

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

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

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




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

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

																	# run embedding layer on everything at once
																	__lowerCAmelCase       =				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
																	__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(_lowerCAmelCase       ,    _lowerCAmelCase       ,    _lowerCAmelCase				)
																						pooled_output_list.append(_lowerCAmelCase				)
																	return torch.cat(_lowerCAmelCase       ,    dim=0				)




							def 							A__	(			self       ,    _A       ,    _A=None       ,    _A=-1       ,    ):
												__lowerCAmelCase       =				self.embed_sentences_checkpointed(
												    _lowerCAmelCase       ,    _lowerCAmelCase       ,    self.bert_query       ,    _lowerCAmelCase       ,    )
												return self.project_query(_lowerCAmelCase				)




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







import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_  							=			logging.get_logger(__name__)

lowercase_  							=			{
    "facebook/hubert-base-ls960": "https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json",
    # See all Hubert models at https://huggingface.co/models?filter=hubert
}







class      SCREAMING_SNAKE_CASE__					(  __UpperCamelCase    ):
       A							:	List[str]          =	"hubert"

       def __init__(							self					:     List[str]			,			_lowerCAmelCase					:     Union[str, Any]=32			,			_lowerCAmelCase					:     Any=7_68			,			_lowerCAmelCase					:     Optional[Any]=12			,			_lowerCAmelCase					:     Optional[int]=12			,			_lowerCAmelCase					:     int=30_72			,			_lowerCAmelCase					:     Optional[Any]="gelu"			,			_lowerCAmelCase					:     List[str]=0.1			,			_lowerCAmelCase					:     Any=0.1			,			_lowerCAmelCase					:     List[str]=0.1			,			_lowerCAmelCase					:     Dict=True			,			_lowerCAmelCase					:     Dict=0.0			,			_lowerCAmelCase					:     List[str]=0.1			,			_lowerCAmelCase					:     Optional[int]=0.1			,			_lowerCAmelCase					:     Dict=0.02			,			_lowerCAmelCase					:     Any=1e-5			,			_lowerCAmelCase					:     str="group"			,			_lowerCAmelCase					:     Any="gelu"			,			_lowerCAmelCase					:     List[str]=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12)			,			_lowerCAmelCase					:     Any=(5, 2, 2, 2, 2, 2, 2)			,			_lowerCAmelCase					:     Dict=(10, 3, 3, 3, 3, 2, 2)			,			_lowerCAmelCase					:     List[str]=False			,			_lowerCAmelCase					:     Optional[Any]=1_28			,			_lowerCAmelCase					:     int=16			,			_lowerCAmelCase					:     Tuple=False			,			_lowerCAmelCase					:     int=True			,			_lowerCAmelCase					:     int=0.05			,			_lowerCAmelCase					:     Any=10			,			_lowerCAmelCase					:     Dict=2			,			_lowerCAmelCase					:     Dict=0.0			,			_lowerCAmelCase					:     Optional[int]=10			,			_lowerCAmelCase					:     Union[str, Any]=0			,			_lowerCAmelCase					:     int="sum"			,			_lowerCAmelCase					:     Optional[int]=False			,			_lowerCAmelCase					:     str=False			,			_lowerCAmelCase					:     Optional[Any]=2_56			,			_lowerCAmelCase					:     Any=0			,			_lowerCAmelCase					:     List[Any]=1			,			_lowerCAmelCase					:     List[str]=2			,			**_lowerCAmelCase					:     Optional[int]			,			):
           super().__init__(**_lowerCAmelCase			,			pad_token_id=_lowerCAmelCase			,			bos_token_id=_lowerCAmelCase			,			eos_token_id=_lowerCAmelCase			)
           __snake_case       :				Optional[int] 			=    hidden_size
           __snake_case       :				Optional[Any] 			=    feat_extract_norm
           __snake_case       :				Optional[int] 			=    feat_extract_activation
           __snake_case       :				List[str] 			=    list(_lowerCAmelCase			)
           __snake_case       :				Any 			=    list(_lowerCAmelCase			)
           __snake_case       :				List[Any] 			=    list(_lowerCAmelCase			)
           __snake_case       :				Any 			=    conv_bias
           __snake_case       :				Tuple 			=    num_conv_pos_embeddings
           __snake_case       :				List[Any] 			=    num_conv_pos_embedding_groups
           __snake_case       :				Union[str, Any] 			=    len(self.conv_dim			)
           __snake_case       :				List[Any] 			=    num_hidden_layers
           __snake_case       :				Tuple 			=    intermediate_size
           __snake_case       :				Optional[int] 			=    hidden_act
           __snake_case       :				Union[str, Any] 			=    num_attention_heads
           __snake_case       :				str 			=    hidden_dropout
           __snake_case       :				Union[str, Any] 			=    attention_dropout
           __snake_case       :				Dict 			=    activation_dropout
           __snake_case       :				List[Any] 			=    feat_proj_layer_norm
           __snake_case       :				List[str] 			=    feat_proj_dropout
           __snake_case       :				List[Any] 			=    final_dropout
           __snake_case       :				str 			=    layerdrop
           __snake_case       :				List[str] 			=    layer_norm_eps
           __snake_case       :				Optional[Any] 			=    initializer_range
           __snake_case       :				Optional[int] 			=    vocab_size
           __snake_case       :				Dict 			=    do_stable_layer_norm
           __snake_case       :				Tuple 			=    use_weighted_layer_sum
           __snake_case       :				List[Any] 			=    classifier_proj_size

           if (
               (len(self.conv_stride			) != self.num_feat_extract_layers)
               or (len(self.conv_kernel			) != self.num_feat_extract_layers)
               or (len(self.conv_dim			) != self.num_feat_extract_layers)
           ):
               raise ValueError(
                   """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                   """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                   f''' {len(self.conv_dim			)}`, `len(config.conv_stride) = {len(self.conv_stride			)}`,'''
                   f''' `len(config.conv_kernel) = {len(self.conv_kernel			)}`.'''			)

           # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
           __snake_case       :				Union[str, Any] 			=    apply_spec_augment
           __snake_case       :				List[str] 			=    mask_time_prob
           __snake_case       :				Dict 			=    mask_time_length
           __snake_case       :				int 			=    mask_time_min_masks
           __snake_case       :				List[str] 			=    mask_feature_prob
           __snake_case       :				Tuple 			=    mask_feature_length
           __snake_case       :				int 			=    mask_feature_min_masks

           # ctc loss
           __snake_case       :				Dict 			=    ctc_loss_reduction
           __snake_case       :				List[str] 			=    ctc_zero_infinity





       @property
       def 			snake_case__    (							self					:     Any			):
           return functools.reduce(operator.mul			,			self.conv_stride			,			1			)



