


"""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[Any]          =							logging.get_logger(__name__)

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




class  __snake_case      (lowerCamelCase     ):
							__a				   =					RetriBertConfig
							__a				   =					None
							__a				   =					'''retribert'''




							def      __a      (    self:						Dict    ,       A_:						Optional[Any]      ):
										if isinstance(A_    ,       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(A_    ,       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(A_    ,       nn.LayerNorm      ):
													module.bias.data.zero_()
													module.weight.data.fill_(1.0      )

__magic_name__	:   Dict          =							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  __snake_case      (lowerCamelCase     ):




							def __init__(    self:						int    ,       A_:						RetriBertConfig      ):
										super().__init__(A_      )
										__lowerCamelCase        =			config.projection_dim

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

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

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




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

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

													# run embedding layer on everything at once
													__lowerCamelCase        =			sent_encoder.embeddings(
													    input_ids=A_    ,       position_ids=A_    ,       token_type_ids=A_    ,       inputs_embeds=A_      )
													# 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(A_    ,       A_    ,       A_      )
																pooled_output_list.append(A_      )
													return torch.cat(A_    ,       dim=0      )




							def      __a      (    self:						str    ,       A_:						List[Any]    ,       A_:						Dict=None    ,       A_:						Optional[Any]=-1    ,       ):
										__lowerCamelCase        =			self.embed_sentences_checkpointed(
										    A_    ,       A_    ,       self.bert_query    ,       A_    ,       )
										return self.project_query(A_      )




							def      __a      (    self:						Dict    ,       A_:						int    ,       A_:						List[str]=None    ,       A_:						int=-1    ,       ):
										__lowerCamelCase        =			self.embed_sentences_checkpointed(
										    A_    ,       A_    ,       self.bert_query if self.bert_doc is None else self.bert_doc    ,       A_    ,       )
										return self.project_doc(A_      )




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








"""simple docstring"""




import unittest

from transformers import load_tool
from transformers.tools.agent_types import AGENT_TYPE_MAPPING

from .test_tools_common import ToolTesterMixin, output_types




class  __snake_case      (unittest.TestCase ,		lowerCamelCase     ):




							def      __a      (    self:						Optional[Any]      ):
										__lowerCamelCase        =			load_tool("""translation"""      )
										self.tool.setup()
										__lowerCamelCase        =			load_tool("""translation"""    ,       remote=A_      )




							def      __a      (    self:						int      ):
										__lowerCamelCase        =			self.tool("""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )




							def      __a      (    self:						int      ):
										__lowerCamelCase        =			self.remote_tool("""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )




							def      __a      (    self:						Union[str, Any]      ):
										__lowerCamelCase        =			self.tool(text="""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )




							def      __a      (    self:						Any      ):
										__lowerCamelCase        =			self.remote_tool(text="""Hey, what's up?"""    ,       src_lang="""English"""    ,       tgt_lang="""French"""      )
										self.assertEqual(A_    ,       """- Hé, comment ça va?"""      )




							def      __a      (    self:						List[Any]      ):
										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]
										__lowerCamelCase        =			self.tool(*A_      )

										# There is a single output
										if len(self.tool.outputs      ) == 1:
													__lowerCamelCase        =			[outputs]

										self.assertListEqual(output_types(A_      )    ,       self.tool.outputs      )




							def      __a      (    self:						Union[str, Any]      ):
										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]
										__lowerCamelCase        =			self.tool(*A_      )

										if not isinstance(A_    ,       A_      ):
													__lowerCamelCase        =			[outputs]

										self.assertEqual(len(A_      )    ,       len(self.tool.outputs      )      )

										for output, output_type in zip(A_    ,       self.tool.outputs      ):
													__lowerCamelCase        =			AGENT_TYPE_MAPPING[output_type]
													self.assertTrue(isinstance(A_    ,       A_      )      )




							def      __a      (    self:						Dict      ):
										__lowerCamelCase        =			["""Hey, what's up?""", """English""", """Spanish"""]

										__lowerCamelCase        =			[]

										for _input, input_type in zip(A_    ,       self.tool.inputs      ):
													if isinstance(A_    ,       A_      ):
																_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input      ) for _input_type in input_type]      )
													else:
																_inputs.append(AGENT_TYPE_MAPPING[input_type](_input      )      )

        # Should not raise an error
										__lowerCamelCase        =			self.tool(*A_      )

										if not isinstance(A_    ,       A_      ):
													__lowerCamelCase        =			[outputs]

										self.assertEqual(len(A_      )    ,       len(self.tool.outputs      )      )




