


'''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


__magic_name__   :   Optional[int]  							=logging.get_logger(__name__)

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






class 		UpperCamelCase_		(					_a   ):





						"""simple docstring"""




						UpperCAmelCase__	:       int         =     RetriBertConfig
						UpperCAmelCase__	:       Optional[int]         =     None
						UpperCAmelCase__	:       Any         =     'retribert'
						def 					__A					( self				:					List[Any]	,				_lowerCamelCase				:					Tuple  )							->					str:
										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  )





__magic_name__   :   List[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 		UpperCamelCase_		(					_a   ):





						"""simple docstring"""




						def __init__( self				:					Dict	,				_lowerCamelCase				:					RetriBertConfig  )							->					None:
										super().__init__(_lowerCamelCase  )
										__magic_name__	  = config.projection_dim

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

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

										# Initialize weights and apply final processing
										self.post_init()
						def 					__A					( self				:					List[str]	,				_lowerCamelCase				:					Dict	,				_lowerCamelCase				:					Tuple	,				_lowerCamelCase				:					Tuple	,				_lowerCamelCase				:					Optional[int]=-1	,				)							->					Dict:
										# 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
														__magic_name__	  = input_ids.device
														__magic_name__	  = input_ids.size()
														__magic_name__	  = torch.zeros(_lowerCamelCase	,				dtype=torch.long	,				device=_lowerCamelCase  )
														__magic_name__	  = [None] * sent_encoder.config.num_hidden_layers
														__magic_name__	  = sent_encoder.get_extended_attention_mask(
														    _lowerCamelCase	,				_lowerCamelCase  )

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

														# run embedding layer on everything at once
														__magic_name__	  = 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
														__magic_name__	  = []
														for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size  )  ):
																		__magic_name__	  = embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																		__magic_name__	  = extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
																		__magic_name__	  = checkpoint.checkpoint(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase  )
																		pooled_output_list.append(_lowerCamelCase  )
														return torch.cat(_lowerCamelCase	,				dim=0  )
						def 					__A					( self				:					List[Any]	,				_lowerCamelCase				:					Dict	,				_lowerCamelCase				:					List[Any]=None	,				_lowerCamelCase				:					str=-1	,				)							->					Dict:
										__magic_name__	  = self.embed_sentences_checkpointed(
										    _lowerCamelCase	,				_lowerCamelCase	,				self.bert_query	,				_lowerCamelCase	,				)
										return self.project_query(_lowerCamelCase  )
						def 					__A					( self				:					Optional[Any]	,				_lowerCamelCase				:					Optional[Any]	,				_lowerCamelCase				:					Optional[Any]=None	,				_lowerCamelCase				:					List[Any]=-1	,				)							->					List[str]:
										__magic_name__	  = 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				:					int	,				_lowerCamelCase				:					torch.LongTensor	,				_lowerCamelCase				:					Optional[torch.FloatTensor]	,				_lowerCamelCase				:					torch.LongTensor	,				_lowerCamelCase				:					Optional[torch.FloatTensor]	,				_lowerCamelCase				:					int = -1	,				)							->					torch.FloatTensor:
										__magic_name__	  = input_ids_query.device
										__magic_name__	  = self.embed_questions(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase  )
										__magic_name__	  = self.embed_answers(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase  )
										__magic_name__	  = torch.mm(_lowerCamelCase	,				a_reps.t()  )
										__magic_name__	  = self.ce_loss(_lowerCamelCase	,				torch.arange(compare_scores.shape[1]  ).to(_lowerCamelCase  )  )
										__magic_name__	  = self.ce_loss(compare_scores.t()	,				torch.arange(compare_scores.shape[0]  ).to(_lowerCamelCase  )  )
										__magic_name__	  = (loss_qa + loss_aq) / 2
										return loss







'''simple docstring'''
from __future__ import annotations




def      __snake_case       (       lowerCamelCase_ :				list[list[int]]	,  lowerCamelCase_ :				list[list[int]]						):
				'''simple docstring'''




				assert len(lowerCamelCase_						) == len(lowerCamelCase_						)

				__magic_name__	  = len(lowerCamelCase_						)
				__magic_name__	  = list(range(lowerCamelCase_						)						)
				__magic_name__	  = [-1] * n  # who the donor has donated to
				__magic_name__	  = [-1] * n  # who the recipient has received from
				__magic_name__	  = [0] * n

				while unmatched_donors:
								__magic_name__	  = unmatched_donors[0]
								__magic_name__	  = donor_pref[donor]
								__magic_name__	  = donor_preference[num_donations[donor]]
								num_donations[donor] += 1
								__magic_name__	  = recipient_pref[recipient]
								__magic_name__	  = rec_record[recipient]

								if prev_donor != -1:
												if rec_preference.index(lowerCamelCase_						) > rec_preference.index(lowerCamelCase_						):
																__magic_name__	  = donor
																__magic_name__	  = recipient
																unmatched_donors.append(lowerCamelCase_						)
																unmatched_donors.remove(lowerCamelCase_						)
								else:
												__magic_name__	  = donor
												__magic_name__	  = recipient
												unmatched_donors.remove(lowerCamelCase_						)
				return donor_record



