





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


A_        =  logging.get_logger(__name__)

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

class SCREAMING_SNAKE_CASE_			(       lowercase_ ):





					"""simple docstring"""


					A__								=     RetriBertConfig
					A__								=     None
					A__								=     "retribert"





					def        __magic_name__			(			self						,	_lowerCAmelCase						):
										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						)

A_        =  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."				,							lowercase_				,							)
class SCREAMING_SNAKE_CASE_			(       lowercase_ ):





					"""simple docstring"""


					def __init__(			self						,	_lowerCAmelCase						):
										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        __magic_name__			(			self						,	_lowerCAmelCase						,	_lowerCAmelCase						,	_lowerCAmelCase						,	_lowerCAmelCase=-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(*_lowerCAmelCase						):
																				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        __magic_name__			(			self						,	_lowerCAmelCase						,	_lowerCAmelCase=None						,	_lowerCAmelCase=-1						,	):
										lowerCamelCase__      =							self.embed_sentences_checkpointed(
										    _lowerCAmelCase						,	_lowerCAmelCase						,	self.bert_query						,	_lowerCAmelCase						,	)
										return self.project_query(_lowerCAmelCase						)





					def        __magic_name__			(			self						,	_lowerCAmelCase						,	_lowerCAmelCase=None						,	_lowerCAmelCase=-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        __magic_name__			(			self						,	_lowerCAmelCase						,	_lowerCAmelCase						,	_lowerCAmelCase						,	_lowerCAmelCase						,	_lowerCAmelCase = -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








from typing import Any

import numpy as np





def  __UpperCamelCase   (     a)			->bool:
					assert np.shape(a)[0] == np.shape(a)[1]

					# If matrix not symmetric, exit right away.
					if np.allclose(a,  matrix.T) is False:
										return False

					# Get eigenvalues and eignevectors for a symmetric matrix.
					lowerCamelCase__     ,		lowerCamelCase__      =							np.linalg.eigh(a)

					# Check sign of all eigenvalues.
					# np.all returns a value of type np.bool_
					return bool(np.all(eigen_values > 0))





def  __UpperCamelCase   (     a)			->Any:
					lowerCamelCase__      =							np.random.randn(a,  a)
					lowerCamelCase__      =							np.dot(a,  random_matrix.T)
					assert _is_matrix_spd(a)
					return spd_matrix





def  __UpperCamelCase   (     a,  a,  a = 1000,  a = 1E-8,  )			->Any:
					assert np.shape(a)[0] == np.shape(a)[1]
					assert np.shape(a)[0] == np.shape(a)[0]
					assert _is_matrix_spd(a)

					# Initialize solution guess, residual, search direction.
					lowerCamelCase__      =							np.zeros((np.shape(a)[0], 1))
					lowerCamelCase__      =							np.copy(a)
					lowerCamelCase__      =							np.copy(a)

					# Set initial errors in solution guess and residual.
					lowerCamelCase__      =							1E9
					lowerCamelCase__      =							1E9
					lowerCamelCase__      =							1E9

					# Set iteration counter to threshold number of iterations.
					lowerCamelCase__      =							0

					while error > tol:
										# Save this value so we only calculate the matrix-vector product once.
										lowerCamelCase__      =							np.dot(a,  a)

										# The main algorithm.

										# Update search direction magnitude.
										lowerCamelCase__      =							np.dot(ra.T,  a) / np.dot(pa.T,  a)
										# Update solution guess.
										lowerCamelCase__      =							xa + alpha * pa
										# Calculate new residual.
										lowerCamelCase__      =							ra - alpha * w
										# Calculate new Krylov subspace scale.
										lowerCamelCase__      =							np.dot(r.T,  a) / np.dot(ra.T,  a)
										# Calculate new A conjuage search direction.
										lowerCamelCase__      =							r + beta * pa

										# Calculate errors.
										lowerCamelCase__      =							np.linalg.norm(r - ra)
										lowerCamelCase__      =							np.linalg.norm(x - xa)
										lowerCamelCase__      =							np.maximum(a,  a)

										# Update variables.
										lowerCamelCase__      =							np.copy(a)
										lowerCamelCase__      =							np.copy(a)
										lowerCamelCase__      =							np.copy(a)

										# Update number of iterations.
										iterations += 1
										if iterations > max_iterations:
															break

					return x





def  __UpperCamelCase   (     )			->None:
					lowerCamelCase__      =							3
					lowerCamelCase__      =							_create_spd_matrix(a)
					lowerCamelCase__      =							np.random.randn(a,  1)
					lowerCamelCase__      =							np.dot(a,  a)

					# Numpy solution.
					lowerCamelCase__      =							np.linalg.solve(a,  a)

					# Our implementation.
					lowerCamelCase__      =							conjugate_gradient(a,  a)

					# Ensure both solutions are close to x_true (and therefore one another).
					assert np.linalg.norm(x_numpy - x_true) <= 1E-6
					assert np.linalg.norm(x_conjugate_gradient - x_true) <= 1E-6


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						test_conjugate_gradient()

