



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


UpperCAmelCase :				Dict							=logging.get_logger(__name__)

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


class    _lowercase (a_   ):
				'''simple docstring'''







				lowercase__     =    RetriBertConfig
				lowercase__     =    None
				lowercase__     =    """retribert"""

				def    _lowerCamelCase       (			self  ,			snake_case__     ):

									'''simple docstring'''


									if isinstance(snake_case__  ,			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(snake_case__  ,			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(snake_case__  ,			nn.LayerNorm     ):
														module.bias.data.zero_()
														module.weight.data.fill_(1.0     )




UpperCAmelCase :				Tuple							=r"""

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""


@add_start_docstrings(
    """Bert Based model to embed queries or document for document retrieval."""   , a_   , )
class    _lowercase (a_   ):
				'''simple docstring'''







				def __init__(			self  ,			snake_case__     ):

									'''simple docstring'''


									super().__init__(snake_case__     )
									UpperCamelCase_			= config.projection_dim

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

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

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

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
														return sent_encoder(snake_case__  ,			attention_mask=snake_case__     )[1]
									else:
														# prepare implicit variables
														UpperCamelCase_			= input_ids.device
														UpperCamelCase_			= input_ids.size()
														UpperCamelCase_			= torch.zeros(snake_case__  ,			dtype=torch.long  ,			device=snake_case__     )
														UpperCamelCase_			= [None] * sent_encoder.config.num_hidden_layers
														UpperCamelCase_			= sent_encoder.get_extended_attention_mask(
														    snake_case__  ,			snake_case__     )

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

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

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__=None  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.embed_sentences_checkpointed(
									    snake_case__  ,			snake_case__  ,			self.bert_query  ,			snake_case__  ,			)
									return self.project_query(snake_case__     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__=None  ,			snake_case__=-1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= self.embed_sentences_checkpointed(
									    snake_case__  ,			snake_case__  ,			self.bert_query if self.bert_doc is None else self.bert_doc  ,			snake_case__  ,			)
									return self.project_doc(snake_case__     )

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__ = -1  ,			):

									'''simple docstring'''


									UpperCamelCase_			= input_ids_query.device
									UpperCamelCase_			= self.embed_questions(snake_case__  ,			snake_case__  ,			snake_case__     )
									UpperCamelCase_			= self.embed_answers(snake_case__  ,			snake_case__  ,			snake_case__     )
									UpperCamelCase_			= torch.mm(snake_case__  ,			a_reps.t()     )
									UpperCamelCase_			= self.ce_loss(snake_case__  ,			torch.arange(compare_scores.shape[1]     ).to(snake_case__     )     )
									UpperCamelCase_			= self.ce_loss(compare_scores.t()  ,			torch.arange(compare_scores.shape[0]     ).to(snake_case__     )     )
									UpperCamelCase_			= (loss_qa + loss_aq) / 2
									return loss





import unittest

import pytest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    MBartaaTokenizerFast,
    MBartConfig,
    MBartForConditionalGeneration,
    TranslationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch, slow

from .test_pipelines_common import ANY


@is_pipeline_test
class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				lowercase__     =    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
				lowercase__     =    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									if isinstance(model.config  ,			snake_case__     ):
														UpperCamelCase_	,     UpperCamelCase_			= list(tokenizer.lang_code_to_id.keys()     )[:2]
														UpperCamelCase_			= TranslationPipeline(model=snake_case__  ,			tokenizer=snake_case__  ,			src_lang=snake_case__  ,			tgt_lang=snake_case__     )
									else:
														UpperCamelCase_			= TranslationPipeline(model=snake_case__  ,			tokenizer=snake_case__     )
									return translator, ["Some string", "Some other text"]

				def    _lowerCamelCase       (			self  ,			snake_case__  ,			snake_case__     ):

									'''simple docstring'''


									UpperCamelCase_			= translator("Some string"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}]     )

									UpperCamelCase_			= translator(["Some string"]     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}]     )

									UpperCamelCase_			= translator(["Some string", "other string"]     )
									self.assertEqual(snake_case__  ,			[{"translation_text": ANY(snake_case__     )}, {"translation_text": ANY(snake_case__     )}]     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_ro"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="pt"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide"
									                " Beide Beide"
									            )
									        }
									    ]  ,			)

				@require_tf
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_ro"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="tf"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide"
									                " Beide Beide"
									            )
									        }
									    ]  ,			)

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_de"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="pt"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine"
									                " urine urine urine urine urine urine urine"
									            )
									        }
									    ]  ,			)

				@require_tf
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= pipeline("translation_en_to_de"  ,			model="patrickvonplaten/t5-tiny-random"  ,			framework="tf"     )
									UpperCamelCase_			= translator("This is a test string"  ,			max_length=20     )
									self.assertEqual(
									    snake_case__  ,			[
									        {
									            "translation_text": (
									                "monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine"
									                " urine urine urine urine urine urine urine"
									            )
									        }
									    ]  ,			)




class    _lowercase (unittest.TestCase   ):
				'''simple docstring'''







				@require_torch
				@slow
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									with self.assertRaises(snake_case__     ):
														pipeline(task="translation_cn_to_ar"     )

									# but we do for this one
									UpperCamelCase_			= pipeline(task="translation_en_to_de"     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"en"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"de"     )

				@require_torch
				@slow
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt"     )
									UpperCamelCase_			= MBartaaTokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt"     )

									UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__  ,			tokenizer=snake_case__     )
									# Missing src_lang, tgt_lang
									with self.assertRaises(snake_case__     ):
														translator("This is a test"     )

									UpperCamelCase_			= translator("This is a test"  ,			src_lang="en_XX"  ,			tgt_lang="ar_AR"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "هذا إختبار"}]     )

									UpperCamelCase_			= translator("This is a test"  ,			src_lang="en_XX"  ,			tgt_lang="hi_IN"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "यह एक परीक्षण है"}]     )

									# src_lang, tgt_lang can be defined at pipeline call time
									UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__  ,			tokenizer=snake_case__  ,			src_lang="en_XX"  ,			tgt_lang="ar_AR"     )
									UpperCamelCase_			= translator("This is a test"     )
									self.assertEqual(snake_case__  ,			[{"translation_text": "هذا إختبار"}]     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= "patrickvonplaten/t5-tiny-random"
									UpperCamelCase_			= pipeline(task="translation_cn_to_ar"  ,			model=snake_case__     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"cn"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"ar"     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									UpperCamelCase_			= "patrickvonplaten/t5-tiny-random"
									with pytest.warns(snake_case__  ,			match=R".*translation_en_to_de.*"     ):
														UpperCamelCase_			= pipeline(task="translation"  ,			model=snake_case__     )
									self.assertEqual(translator.task  ,			"translation_en_to_de"     )
									self.assertEqual(translator._preprocess_params["src_lang"]  ,			"en"     )
									self.assertEqual(translator._preprocess_params["tgt_lang"]  ,			"de"     )

				@require_torch
				def    _lowerCamelCase       (			self     ):

									'''simple docstring'''


									with self.assertRaises(snake_case__     ):
														pipeline(task="translation"     )
