



'''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      __UpperCAmelCase							(    lowerCAmelCase							):



					'''simple docstring'''





					_UpperCamelCase  	=		RetriBertConfig
					_UpperCamelCase  	=		None
					_UpperCamelCase  	=		"""retribert"""



					def 						__snake_case	(  self    :	Optional[Any]			,					_lowercase    :	Union[str, Any])						->       List[Any]:
								if isinstance(_lowercase			,					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(_lowercase			,					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(_lowercase			,					nn.LayerNorm):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0)





_SCREAMING_SNAKE_CASE =	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.""" ,lowerCAmelCase ,)
class      __UpperCAmelCase							(    lowerCAmelCase							):



					'''simple docstring'''





					def __init__(  self    :	List[str]			,					_lowercase    :	RetriBertConfig)						->       None:
								super().__init__(_lowercase)
								A_       		=   config.projection_dim

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

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

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



					def 						__snake_case	(  self    :	str			,					_lowercase    :	Any			,					_lowercase    :	Union[str, Any]			,					_lowercase    :	Optional[Any]			,					_lowercase    :	Tuple=-1			,					)						->       Any:
								# reproduces BERT forward pass with checkpointing
								if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
											return sent_encoder(_lowercase			,					attention_mask=_lowercase)[1]
								else:
											# prepare implicit variables
											A_       		=   input_ids.device
											A_       		=   input_ids.size()
											A_       		=   torch.zeros(_lowercase			,					dtype=torch.long			,					device=_lowercase)
											A_       		=   [None] * sent_encoder.config.num_hidden_layers
											A_       		=   sent_encoder.get_extended_attention_mask(
											    _lowercase			,					_lowercase)

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

											# run embedding layer on everything at once
											A_       		=   sent_encoder.embeddings(
											    input_ids=_lowercase			,					position_ids=_lowercase			,					token_type_ids=_lowercase			,					inputs_embeds=_lowercase)
											# run encoding and pooling on one mini-batch at a time
											A_       		=   []
											for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
														A_       		=   embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
														A_       		=   extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
														A_       		=   checkpoint.checkpoint(_lowercase			,					_lowercase			,					_lowercase)
														pooled_output_list.append(_lowercase)
											return torch.cat(_lowercase			,					dim=0)



					def 						__snake_case	(  self    :	Optional[int]			,					_lowercase    :	List[str]			,					_lowercase    :	Optional[Any]=None			,					_lowercase    :	Tuple=-1			,					)						->       List[str]:
								A_       		=   self.embed_sentences_checkpointed(
								    _lowercase			,					_lowercase			,					self.bert_query			,					_lowercase			,					)
								return self.project_query(_lowercase)



					def 						__snake_case	(  self    :	Any			,					_lowercase    :	List[str]			,					_lowercase    :	Dict=None			,					_lowercase    :	int=-1			,					)						->       Union[str, Any]:
								A_       		=   self.embed_sentences_checkpointed(
								    _lowercase			,					_lowercase			,					self.bert_query if self.bert_doc is None else self.bert_doc			,					_lowercase			,					)
								return self.project_doc(_lowercase)



					def 						__snake_case	(  self    :	int			,					_lowercase    :	torch.LongTensor			,					_lowercase    :	Optional[torch.FloatTensor]			,					_lowercase    :	torch.LongTensor			,					_lowercase    :	Optional[torch.FloatTensor]			,					_lowercase    :	int = -1			,					)						->       torch.FloatTensor:
								A_       		=   input_ids_query.device
								A_       		=   self.embed_questions(_lowercase			,					_lowercase			,					_lowercase)
								A_       		=   self.embed_answers(_lowercase			,					_lowercase			,					_lowercase)
								A_       		=   torch.mm(_lowercase			,					a_reps.t())
								A_       		=   self.ce_loss(_lowercase			,					torch.arange(compare_scores.shape[1]).to(_lowercase))
								A_       		=   self.ce_loss(compare_scores.t()			,					torch.arange(compare_scores.shape[0]).to(_lowercase))
								A_       		=   (loss_qa + loss_aq) / 2
								return loss










'''simple docstring'''
import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_SCREAMING_SNAKE_CASE =	namedtuple("ExampleNamedTuple", "a b c")
class      __UpperCAmelCase							(    unittest.TestCase							):



					'''simple docstring'''





					def 						__snake_case	(  self    :	List[Any])						->       Tuple:
								A_       		=   torch.randn(5			,					2)
								A_       		=   torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

								A_       		=   send_to_device(_lowercase			,					_lowercase)
								self.assertTrue(torch.equal(resulta.cpu()			,					_lowercase))

								A_       		=   send_to_device((tensor, [tensor, tensor], 1)			,					_lowercase)
								self.assertIsInstance(_lowercase			,					_lowercase)
								self.assertTrue(torch.equal(resulta[0].cpu()			,					_lowercase))
								self.assertIsInstance(resulta[1]			,					_lowercase)
								self.assertTrue(torch.equal(resulta[1][0].cpu()			,					_lowercase))
								self.assertTrue(torch.equal(resulta[1][1].cpu()			,					_lowercase))
								self.assertEqual(resulta[2]			,					1)

								A_       		=   send_to_device({'a': tensor, 'b': [tensor, tensor], 'c': 1}			,					_lowercase)
								self.assertIsInstance(_lowercase			,					_lowercase)
								self.assertTrue(torch.equal(resulta['a'].cpu()			,					_lowercase))
								self.assertIsInstance(resulta['b']			,					_lowercase)
								self.assertTrue(torch.equal(resulta['b'][0].cpu()			,					_lowercase))
								self.assertTrue(torch.equal(resulta['b'][1].cpu()			,					_lowercase))
								self.assertEqual(resulta['c']			,					1)

								A_       		=   send_to_device(ExampleNamedTuple(a=_lowercase			,					b=[tensor, tensor]			,					c=1)			,					_lowercase)
								self.assertIsInstance(_lowercase			,					_lowercase)
								self.assertTrue(torch.equal(resulta.a.cpu()			,					_lowercase))
								self.assertIsInstance(resulta.b			,					_lowercase)
								self.assertTrue(torch.equal(resulta.b[0].cpu()			,					_lowercase))
								self.assertTrue(torch.equal(resulta.b[1].cpu()			,					_lowercase))
								self.assertEqual(resulta.c			,					1)

								A_       		=   send_to_device(UserDict({'a': tensor, 'b': [tensor, tensor], 'c': 1})			,					_lowercase)
								self.assertIsInstance(_lowercase			,					_lowercase)
								self.assertTrue(torch.equal(resulta['a'].cpu()			,					_lowercase))
								self.assertIsInstance(resulta['b']			,					_lowercase)
								self.assertTrue(torch.equal(resulta['b'][0].cpu()			,					_lowercase))
								self.assertTrue(torch.equal(resulta['b'][1].cpu()			,					_lowercase))
								self.assertEqual(resulta['c']			,					1)



					def 						__snake_case	(  self    :	Dict)						->       str:
								with self.assertRaises(_lowercase) as cm:
											A_       		=   recursively_apply(torch.tensor			,					(torch.tensor(1), 1)			,					error_on_other_type=_lowercase)
								self.assertEqual(
								    str(cm.exception)			,					'Unsupported types (<class \'int\'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.'			,					)



					def 						__snake_case	(  self    :	Union[str, Any])						->       List[str]:
								A_       		=   torch.tensor([1, 2, 3, 4, 5])
								self.assertEqual(listify(_lowercase)			,					[1, 2, 3, 4, 5])

								A_       		=   torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
								self.assertEqual(listify(_lowercase)			,					[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

								A_       		=   torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]])
								self.assertEqual(
								    listify(_lowercase)			,					[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]])



					def 						__snake_case	(  self    :	List[Any])						->       Union[str, Any]:
								with patch_environment(aa=1			,					BB=2):
											self.assertEqual(os.environ.get('AA')			,					'1')
											self.assertEqual(os.environ.get('BB')			,					'2')

								self.assertNotIn('AA'			,					os.environ)
								self.assertNotIn('BB'			,					os.environ)



					def 						__snake_case	(  self    :	Any)						->       str:
								A_       		=   RegressionModel()
								A_       		=   model.forward
								A_       		=   convert_outputs_to_fpaa(model.forward)
								A_       		=   extract_model_from_parallel(_lowercase			,					keep_fpaa_wrapper=_lowercase)
								A_       		=   pickle.dumps(_lowercase)



					@require_cuda
					def 						__snake_case	(  self    :	Union[str, Any])						->       Union[str, Any]:
								A_       		=   RegressionModel()
								A_       		=   model.forward
								A_       		=   torch.cuda.amp.autocast(dtype=torch.floataa)(model.forward)
								A_       		=   convert_outputs_to_fpaa(model.forward)
								A_       		=   extract_model_from_parallel(_lowercase			,					keep_fpaa_wrapper=_lowercase)
								A_       		=   pickle.dumps(_lowercase)



					@require_cuda
					@require_torch_min_version(version='2.0')
					def 						__snake_case	(  self    :	Optional[Any])						->       Dict:
								A_       		=   RegressionModel()
								A_       		=   model.forward
								A_       		=   torch.cuda.amp.autocast(dtype=torch.floataa)(model.forward)
								A_       		=   convert_outputs_to_fpaa(model.forward)
								A_       		=   torch.compile(model.forward			,					backend='inductor')
								A_       		=   torch.randn(4			,					10).cuda()
								A_       		=   model(_lowercase)



					def 						__snake_case	(  self    :	Union[str, Any])						->       Optional[Any]:
								A_       		=   RegressionModel()
								# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
								A_       		=   torch.nn.parallel.DataParallel(_lowercase)
								A_       		=   extract_model_from_parallel(_lowercase)

								self.assertEqual(_lowercase			,					_lowercase)



					@require_torch_min_version(version='2.0')
					def 						__snake_case	(  self    :	str)						->       int:
								A_       		=   RegressionModel()
								A_       		=   torch.compile(_lowercase)

								# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
								A_       		=   torch.nn.parallel.DataParallel(_lowercase)
								A_       		=   torch.compile(_lowercase)
								A_       		=   extract_model_from_parallel(_lowercase)

								self.assertEqual(compiled_model._orig_mod			,					compiled_model_unwrapped._orig_mod)



					def 						__snake_case	(  self    :	List[str])						->       Optional[int]:
								self.assertEqual(find_device([1, 'a', torch.tensor([1, 2, 3])])			,					torch.device('cpu'))
								self.assertEqual(find_device({'a': 1, 'b': torch.tensor([1, 2, 3])})			,					torch.device('cpu'))
								self.assertIsNone(find_device([1, 'a']))




