

'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers import (
           TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFXLMForMultipleChoice,
           TFXLMForQuestionAnsweringSimple,
           TFXLMForSequenceClassification,
           TFXLMForTokenClassification,
           TFXLMModel,
           TFXLMWithLMHeadModel,
           XLMConfig,
       )


class 					lowerCAmelCase       :







       def __init__(							self     :	Dict  , __lowercase     :	Optional[int]  , ):







            """simple docstring"""







            __lowercase     						=parent
            __lowercase     						=13
            __lowercase     						=7
            __lowercase     						=True
            __lowercase     						=True
            __lowercase     						=True
            __lowercase     						=True
            __lowercase     						=True
            __lowercase     						=False
            __lowercase     						=False
            __lowercase     						=False
            __lowercase     						=2
            __lowercase     						=99
            __lowercase     						=0
            __lowercase     						=32
            __lowercase     						=2
            __lowercase     						=4
            __lowercase     						=0.1
            __lowercase     						=0.1
            __lowercase     						=512
            __lowercase     						=16
            __lowercase     						=2
            __lowercase     						=0.0_2
            __lowercase     						=3
            __lowercase     						=4
            __lowercase     						='last'
            __lowercase     						=True
            __lowercase     						=None
            __lowercase     						=0







       def      snake_case				(							self     :	int ):







            """simple docstring"""







            __lowercase     						=ids_tensor([self.batch_size, self.seq_length]  , self.vocab_size )
            __lowercase     						=random_attention_mask([self.batch_size, self.seq_length]  , dtype=tf.floataa )

            __lowercase     						=None
            if self.use_input_lengths:
                 __lowercase     						=(
                     ids_tensor([self.batch_size]  , vocab_size=2 ) + self.seq_length - 2
                 )  # small variation of seq_length

            __lowercase     						=None
            if self.use_token_type_ids:
                 __lowercase     						=ids_tensor([self.batch_size, self.seq_length]  , self.n_langs )

            __lowercase     						=None
            __lowercase     						=None
            __lowercase     						=None
            if self.use_labels:
                 __lowercase     						=ids_tensor([self.batch_size]  , self.type_sequence_label_size )
                 __lowercase     						=ids_tensor([self.batch_size, self.seq_length]  , self.num_labels )
                 __lowercase     						=ids_tensor([self.batch_size]  , 2  , dtype=tf.floataa )
                 __lowercase     						=ids_tensor([self.batch_size]  , self.num_choices )

            __lowercase     						=XLMConfig(
                vocab_size=self.vocab_size  , n_special=self.n_special  , emb_dim=self.hidden_size  , n_layers=self.num_hidden_layers  , n_heads=self.num_attention_heads  , dropout=self.hidden_dropout_prob  , attention_dropout=self.attention_probs_dropout_prob  , gelu_activation=self.gelu_activation  , sinusoidal_embeddings=self.sinusoidal_embeddings  , asm=self.asm  , causal=self.causal  , n_langs=self.n_langs  , max_position_embeddings=self.max_position_embeddings  , initializer_range=self.initializer_range  , summary_type=self.summary_type  , use_proj=self.use_proj  , bos_token_id=self.bos_token_id  , )

            return (
                config,
                input_ids,
                token_type_ids,
                input_lengths,
                sequence_labels,
                token_labels,
                is_impossible_labels,
                choice_labels,
                input_mask,
            )







       def      snake_case				(							self     :	Optional[Any]  , __lowercase     :	Optional[Any]  , __lowercase     :	List[str]  , __lowercase     :	Optional[int]  , __lowercase     :	List[Any]  , __lowercase     :	Optional[Any]  , __lowercase     :	Union[str, Any]  , __lowercase     :	Union[str, Any]  , __lowercase     :	List[Any]  , __lowercase     :	List[Any]  , ):







            """simple docstring"""







            __lowercase     						=TFXLMModel(config=__lowercase )
            __lowercase     						={'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
            __lowercase     						=model(__lowercase )

            __lowercase     						=[input_ids, input_mask]
            __lowercase     						=model(__lowercase )
            self.parent.assertEqual(result.last_hidden_state.shape  , (self.batch_size, self.seq_length, self.hidden_size) )







       def      snake_case				(							self     :	List[Any]  , __lowercase     :	str  , __lowercase     :	int  , __lowercase     :	Optional[Any]  , __lowercase     :	Any  , __lowercase     :	List[Any]  , __lowercase     :	Optional[int]  , __lowercase     :	List[Any]  , __lowercase     :	List[str]  , __lowercase     :	Union[str, Any]  , ):







            """simple docstring"""







            __lowercase     						=TFXLMWithLMHeadModel(__lowercase )

            __lowercase     						={'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids}
            __lowercase     						=model(__lowercase )

            __lowercase     						=outputs

            self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.seq_length, self.vocab_size) )







       def      snake_case				(							self     :	Optional[int]  , __lowercase     :	Union[str, Any]  , __lowercase     :	str  , __lowercase     :	Union[str, Any]  , __lowercase     :	Union[str, Any]  , __lowercase     :	List[str]  , __lowercase     :	Tuple  , __lowercase     :	Optional[Any]  , __lowercase     :	Tuple  , __lowercase     :	Optional[Any]  , ):







            """simple docstring"""







            __lowercase     						=TFXLMForQuestionAnsweringSimple(__lowercase )

            __lowercase     						={'input_ids': input_ids, 'lengths': input_lengths}

            __lowercase     						=model(__lowercase )

            self.parent.assertEqual(result.start_logits.shape  , (self.batch_size, self.seq_length) )
            self.parent.assertEqual(result.end_logits.shape  , (self.batch_size, self.seq_length) )







       def      snake_case				(							self     :	str  , __lowercase     :	Tuple  , __lowercase     :	Any  , __lowercase     :	List[Any]  , __lowercase     :	List[Any]  , __lowercase     :	int  , __lowercase     :	Tuple  , __lowercase     :	Tuple  , __lowercase     :	List[Any]  , __lowercase     :	List[str]  , ):







            """simple docstring"""







            __lowercase     						=TFXLMForSequenceClassification(__lowercase )

            __lowercase     						={'input_ids': input_ids, 'lengths': input_lengths}

            __lowercase     						=model(__lowercase )

            self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.type_sequence_label_size) )







       def      snake_case				(							self     :	Optional[Any]  , __lowercase     :	Tuple  , __lowercase     :	Tuple  , __lowercase     :	List[Any]  , __lowercase     :	Optional[Any]  , __lowercase     :	Union[str, Any]  , __lowercase     :	Dict  , __lowercase     :	Dict  , __lowercase     :	str  , __lowercase     :	Optional[int]  , ):







            """simple docstring"""







            __lowercase     						=self.num_labels
            __lowercase     						=TFXLMForTokenClassification(config=__lowercase )
            __lowercase     						={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
            __lowercase     						=model(__lowercase )
            self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.seq_length, self.num_labels) )







       def      snake_case				(							self     :	List[str]  , __lowercase     :	List[Any]  , __lowercase     :	Optional[Any]  , __lowercase     :	Union[str, Any]  , __lowercase     :	Tuple  , __lowercase     :	int  , __lowercase     :	Union[str, Any]  , __lowercase     :	str  , __lowercase     :	Tuple  , __lowercase     :	str  , ):







            """simple docstring"""







            __lowercase     						=self.num_choices
            __lowercase     						=TFXLMForMultipleChoice(config=__lowercase )
            __lowercase     						=tf.tile(tf.expand_dims(__lowercase  , 1 )  , (1, self.num_choices, 1) )
            __lowercase     						=tf.tile(tf.expand_dims(__lowercase  , 1 )  , (1, self.num_choices, 1) )
            __lowercase     						=tf.tile(tf.expand_dims(__lowercase  , 1 )  , (1, self.num_choices, 1) )
            __lowercase     						={
                'input_ids': multiple_choice_inputs_ids,
                'attention_mask': multiple_choice_input_mask,
                'token_type_ids': multiple_choice_token_type_ids,
            }
            __lowercase     						=model(__lowercase )
            self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.num_choices) )







       def      snake_case				(							self     :	List[Any] ):







            """simple docstring"""







            __lowercase     						=self.prepare_config_and_inputs()
            (
                (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       (
                __lowercase
            )						,       
            )     						=config_and_inputs
            __lowercase     						={
                'input_ids': input_ids,
                'token_type_ids': token_type_ids,
                'langs': token_type_ids,
                'lengths': input_lengths,
            }
            return config, inputs_dict






@require_tf
class 					lowerCAmelCase       ( A				,     A				,     unittest.TestCase				):
       lowerCAmelCase_				=	(
           (
               TFXLMModel,
               TFXLMWithLMHeadModel,
               TFXLMForSequenceClassification,
               TFXLMForQuestionAnsweringSimple,
               TFXLMForTokenClassification,
               TFXLMForMultipleChoice,
           )
           if is_tf_available()
           else ()
       )
       lowerCAmelCase_				=	(
           (TFXLMWithLMHeadModel,) if is_tf_available() else ()
       )  # TODO (PVP): Check other models whether language generation is also applicable
       lowerCAmelCase_				=	(
           {
               "feature-extraction": TFXLMModel,
               "fill-mask": TFXLMWithLMHeadModel,
               "question-answering": TFXLMForQuestionAnsweringSimple,
               "text-classification": TFXLMForSequenceClassification,
               "text-generation": TFXLMWithLMHeadModel,
               "token-classification": TFXLMForTokenClassification,
               "zero-shot": TFXLMForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       lowerCAmelCase_				=	False
       lowerCAmelCase_				=	False







       def      snake_case				(							self     :	Tuple  , __lowercase     :	List[Any]  , __lowercase     :	Optional[int]  , __lowercase     :	int  , __lowercase     :	List[str]  , __lowercase     :	Optional[Any] ):







            """simple docstring"""







            if (
                pipeline_test_casse_name == "QAPipelineTests"
                and tokenizer_name is not None
                and not tokenizer_name.endswith('Fast' )
            ):
                 # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
                 # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
                 # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
                 return True

            return False







       def      snake_case				(							self     :	List[str] ):







            """simple docstring"""







            __lowercase     						=TFXLMModelTester(self )
            __lowercase     						=ConfigTester(self  , config_class=__lowercase  , emb_dim=37 )







       def      snake_case				(							self     :	Optional[Any] ):







            """simple docstring"""







            self.config_tester.run_common_tests()







       def      snake_case				(							self     :	Any ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_model(*__lowercase )







       def      snake_case				(							self     :	Tuple ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_lm_head(*__lowercase )







       def      snake_case				(							self     :	Tuple ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_qa(*__lowercase )







       def      snake_case				(							self     :	str ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_sequence_classif(*__lowercase )







       def      snake_case				(							self     :	Any ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_for_token_classification(*__lowercase )







       def      snake_case				(							self     :	int ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_xlm_for_multiple_choice(*__lowercase )







       @slow
       def      snake_case				(							self     :	Optional[int] ):







            """simple docstring"""







            for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __lowercase     						=TFXLMModel.from_pretrained(__lowercase )
                 self.assertIsNotNone(__lowercase )






@require_tf
class 					lowerCAmelCase       ( unittest.TestCase				):







       @slow
       def      snake_case				(							self     :	Any ):







            """simple docstring"""







            __lowercase     						=TFXLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' )
            __lowercase     						=tf.convert_to_tensor([[14, 447]]  , dtype=tf.intaa )  # the president
            __lowercase     						=[
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
                14,
                447,
            ]  # the president the president the president the president the president the president the president the president the president the president
            # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
            __lowercase     						=model.generate(__lowercase  , do_sample=__lowercase )
            self.assertListEqual(output_ids[0].numpy().tolist()  , __lowercase )





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


UpperCAmelCase							=					logging.get_logger(__name__)

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


class 					lowerCAmelCase       ( A				):
       lowerCAmelCase_				=	RetriBertConfig
       lowerCAmelCase_				=	None
       lowerCAmelCase_				=	"retribert"







       def      snake_case				(							self     :	Tuple  , __lowercase     :	List[str] ):







            """simple docstring"""







            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 )






UpperCAmelCase							=					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 					lowerCAmelCase       ( A				):







       def __init__(							self     :	int  , __lowercase     :	RetriBertConfig ):







            """simple docstring"""







            super().__init__(__lowercase )
            __lowercase     						=config.projection_dim

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

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

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







       def      snake_case				(							self     :	Dict  , __lowercase     :	List[Any]  , __lowercase     :	Any  , __lowercase     :	Optional[int]  , __lowercase     :	str=-1  , ):







            """simple docstring"""







            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
                 __lowercase     						=input_ids.device
                 __lowercase     						=input_ids.size()
                 __lowercase     						=torch.zeros(__lowercase  , dtype=torch.long  , device=__lowercase )
                 __lowercase     						=[None] * sent_encoder.config.num_hidden_layers
                 __lowercase     						=sent_encoder.get_extended_attention_mask(
                     __lowercase  , __lowercase )

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

                 # run embedding layer on everything at once
                 __lowercase     						=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
                 __lowercase     						=[]
                 for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size ) ):
                      __lowercase     						=embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                      __lowercase     						=extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                      __lowercase     						=checkpoint.checkpoint(__lowercase  , __lowercase  , __lowercase )
                      pooled_output_list.append(__lowercase )
                 return torch.cat(__lowercase  , dim=0 )







       def      snake_case				(							self     :	List[Any]  , __lowercase     :	Any  , __lowercase     :	Any=None  , __lowercase     :	Optional[int]=-1  , ):







            """simple docstring"""







            __lowercase     						=self.embed_sentences_checkpointed(
                __lowercase  , __lowercase  , self.bert_query  , __lowercase  , )
            return self.project_query(__lowercase )







       def      snake_case				(							self     :	Dict  , __lowercase     :	Tuple  , __lowercase     :	Optional[int]=None  , __lowercase     :	Any=-1  , ):







            """simple docstring"""







            __lowercase     						=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  , ):







            """simple docstring"""







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


