






"""simple docstring"""



import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
 from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder


def 	SCREAMING_SNAKE_CASE__       (  snake_case       : int			,					snake_case       : List[Any]			,					snake_case       : Optional[Any]			,					snake_case       : Dict=None			,					snake_case       : int=None			,					snake_case       : Any=None			,					snake_case       : int=None			,					snake_case       : Optional[Any]=None			,					)->		Union[str, Any]:






     '''simple docstring'''



     if attention_mask is None:
          UpperCAmelCase__						:    Any							=							input_ids.ne(config.pad_token_id				)
     if decoder_attention_mask is None:
          UpperCAmelCase__						:    Optional[int]							=							decoder_input_ids.ne(config.pad_token_id				)
     if head_mask is None:
          UpperCAmelCase__						:    Optional[int]							=							torch.ones(config.encoder_layers			,					config.encoder_attention_heads			,					device=snake_case__				)
     if decoder_head_mask is None:
          UpperCAmelCase__						:    Any							=							torch.ones(config.decoder_layers			,					config.decoder_attention_heads			,					device=snake_case__				)
     if cross_attn_head_mask is None:
          UpperCAmelCase__						:    List[Any]							=							torch.ones(config.decoder_layers			,					config.decoder_attention_heads			,					device=snake_case__				)
     return {
         "input_ids": input_ids,
         "decoder_input_ids": decoder_input_ids,
         "attention_mask": attention_mask,
         "decoder_attention_mask": attention_mask,
         "head_mask": head_mask,
         "decoder_head_mask": decoder_head_mask,
         "cross_attn_head_mask": cross_attn_head_mask,
     }




class 			lowerCAmelCase__			:
   def __init__(		self      :	str							,			snake_case__      :	Any							,			snake_case__      :	str=1_3							,			snake_case__      :	Tuple=7							,			snake_case__      :	int=True							,			snake_case__      :	Tuple=False							,			snake_case__      :	List[str]=9_9							,			snake_case__      :	Union[str, Any]=1_6							,			snake_case__      :	Union[str, Any]=2							,			snake_case__      :	List[Any]=4							,			snake_case__      :	List[Any]=4							,			snake_case__      :	Dict="relu"							,			snake_case__      :	List[Any]=0.1							,			snake_case__      :	Optional[Any]=0.1							,			snake_case__      :	List[str]=0.0							,			snake_case__      :	Optional[Any]=0.0							,			snake_case__      :	Optional[Any]=2_0							,			snake_case__      :	List[Any]=2							,			snake_case__      :	Optional[Any]=1							,			snake_case__      :	Tuple=0							,			):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							parent
        UpperCAmelCase__						:    Tuple							=							batch_size
        UpperCAmelCase__						:    List[Any]							=							seq_length
        UpperCAmelCase__						:    str							=							is_training
        UpperCAmelCase__						:    str							=							use_labels
        UpperCAmelCase__						:    List[Any]							=							vocab_size
        UpperCAmelCase__						:    str							=							hidden_size
        UpperCAmelCase__						:    Union[str, Any]							=							num_hidden_layers
        UpperCAmelCase__						:    Dict							=							num_attention_heads
        UpperCAmelCase__						:    Dict							=							intermediate_size
        UpperCAmelCase__						:    str							=							hidden_act
        UpperCAmelCase__						:    Any							=							hidden_dropout_prob
        UpperCAmelCase__						:    str							=							attention_probs_dropout_prob
        UpperCAmelCase__						:    str							=							encoder_layerdrop
        UpperCAmelCase__						:    Dict							=							decoder_layerdrop
        UpperCAmelCase__						:    int							=							max_position_embeddings
        UpperCAmelCase__						:    Union[str, Any]							=							eos_token_id
        UpperCAmelCase__						:    List[Any]							=							pad_token_id
        UpperCAmelCase__						:    Union[str, Any]							=							bos_token_id
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size							)
        UpperCAmelCase__						:    Dict							=							self.eos_token_id  # Eos Token
        UpperCAmelCase__						:    Union[str, Any]							=							ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size							)

        # we need to clamp the input ids here to avoid having pad token in between
        # this is because for M2M100 the position_ids are prepared such that
        # all pad tokens have pos id = 2 and rest are between 2..seq_length
        # and the seq_length here is seq_length - num_pad_tokens
        # but when using past, there is no way of knowing if the past input ids had
        # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
        # position_ids being off by num_pad_tokens in past input
        UpperCAmelCase__						:    int							=							input_ids.clamp(self.pad_token_id + 1							)
        UpperCAmelCase__						:    Dict							=							decoder_input_ids.clamp(self.pad_token_id + 1							)

        UpperCAmelCase__						:    Tuple							=							self.get_config()
        UpperCAmelCase__						:    Union[str, Any]							=							prepare_mam_aaa_inputs_dict(snake_case__							,			snake_case__							,			snake_case__							)
        return config, inputs_dict
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        return MaMaaaConfig(
            vocab_size=self.vocab_size							,			d_model=self.hidden_size							,			encoder_layers=self.num_hidden_layers							,			decoder_layers=self.num_hidden_layers							,			encoder_attention_heads=self.num_attention_heads							,			decoder_attention_heads=self.num_attention_heads							,			encoder_ffn_dim=self.intermediate_size							,			decoder_ffn_dim=self.intermediate_size							,			dropout=self.hidden_dropout_prob							,			attention_dropout=self.attention_probs_dropout_prob							,			encoder_layerdrop=self.encoder_layerdrop							,			decoder_layerdrop=self.decoder_layerdrop							,			max_position_embeddings=self.max_position_embeddings							,			eos_token_id=self.eos_token_id							,			bos_token_id=self.bos_token_id							,			pad_token_id=self.pad_token_id							,			)
   def       __a							(		self      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							self.prepare_config_and_inputs()
        return config, inputs_dict
   def       __a							(		self      :	str							,			snake_case__      :	int							,			snake_case__      :	Tuple							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							MaMaaaModel(config=snake_case__							).get_decoder().to(snake_case__							).eval()
        UpperCAmelCase__						:    Optional[int]							=							inputs_dict['''input_ids''']
        UpperCAmelCase__						:    List[Any]							=							inputs_dict['''attention_mask''']
        UpperCAmelCase__						:    Dict							=							inputs_dict['''head_mask''']

        # first forward pass
        UpperCAmelCase__						:    Tuple							=							model(snake_case__							,			attention_mask=snake_case__							,			head_mask=snake_case__							,			use_cache=snake_case__							)

        UpperCAmelCase__						:    Union[str, Any]							=							outputs.to_tuple()

        # create hypothetical multiple next token and extent to next_input_ids
        UpperCAmelCase__						:    Optional[Any]							=							ids_tensor((self.batch_size, 3)							,			config.vocab_size							)
        UpperCAmelCase__						:    Optional[Any]							=							ids_tensor((self.batch_size, 3)							,			2							)

        # append to next input_ids and
        UpperCAmelCase__						:    Optional[int]							=							torch.cat([input_ids, next_tokens]							,			dim=-1							)
        UpperCAmelCase__						:    str							=							torch.cat([attention_mask, next_attn_mask]							,			dim=-1							)

        UpperCAmelCase__						:    List[Any]							=							model(snake_case__							,			attention_mask=snake_case__							)['''last_hidden_state''']
        UpperCAmelCase__						:    Dict							=							model(snake_case__							,			attention_mask=snake_case__							,			past_key_values=snake_case__							)[
            '''last_hidden_state'''
        ]

        # select random slice
        UpperCAmelCase__						:    int							=							ids_tensor((1,)							,			output_from_past.shape[-1]							).item()
        UpperCAmelCase__						:    List[Any]							=							output_from_no_past[:, -3:, random_slice_idx].detach()
        UpperCAmelCase__						:    Any							=							output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(snake_case__							,			snake_case__							,			atol=1e-2							)							)




   def       __a							(		self      :	Any							,			snake_case__      :	int							,			snake_case__      :	List[str]							):


        '''simple docstring'''
        UpperCAmelCase__						:    str							=							MaMaaaModel(config=snake_case__							).to(snake_case__							).eval()
        UpperCAmelCase__						:    str							=							model(**snake_case__							)

        UpperCAmelCase__						:    Optional[int]							=							outputs.encoder_last_hidden_state
        UpperCAmelCase__						:    Any							=							outputs.last_hidden_state

        with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCAmelCase__						:    List[str]							=							model.get_encoder()
             encoder.save_pretrained(snake_case__							)
             UpperCAmelCase__						:    Optional[Any]							=							MaMaaaEncoder.from_pretrained(snake_case__							).to(snake_case__							)

        UpperCAmelCase__						:    List[Any]							=							encoder(inputs_dict["input_ids"]							,			attention_mask=inputs_dict["attention_mask"]							)[
            0
        ]

        self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3							)

        with tempfile.TemporaryDirectory() as tmpdirname:
             UpperCAmelCase__						:    Tuple							=							model.get_decoder()
             decoder.save_pretrained(snake_case__							)
             UpperCAmelCase__						:    Any							=							MaMaaaDecoder.from_pretrained(snake_case__							).to(snake_case__							)

        UpperCAmelCase__						:    Dict							=							decoder(
            input_ids=inputs_dict["decoder_input_ids"]							,			attention_mask=inputs_dict["decoder_attention_mask"]							,			encoder_hidden_states=snake_case__							,			encoder_attention_mask=inputs_dict["attention_mask"]							,			)[0]

        self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3							)




@require_torch
class 			lowerCAmelCase__			(    __snake_case							,						__snake_case							,						__snake_case							,						unittest.TestCase   ):
   SCREAMING_SNAKE_CASE_    =(
       (
           MaMaaaModel,
           MaMaaaForConditionalGeneration,
       )
       if is_torch_available()
       else ()
   )
   SCREAMING_SNAKE_CASE_    =(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
   SCREAMING_SNAKE_CASE_    =(
       {
           '''conversational''': MaMaaaForConditionalGeneration,
           '''feature-extraction''': MaMaaaModel,
           '''summarization''': MaMaaaForConditionalGeneration,
           '''text2text-generation''': MaMaaaForConditionalGeneration,
           '''translation''': MaMaaaForConditionalGeneration,
       }
       if is_torch_available()
       else {}
   )
   SCREAMING_SNAKE_CASE_    =True
   SCREAMING_SNAKE_CASE_    =True
   SCREAMING_SNAKE_CASE_    =False
   SCREAMING_SNAKE_CASE_    =False
   def       __a							(		self      :	int							,			snake_case__      :	Tuple							,			snake_case__      :	List[Any]							,			snake_case__      :	Any							,			snake_case__      :	Tuple							,			snake_case__      :	str							):


        '''simple docstring'''






        if pipeline_test_casse_name == "TranslationPipelineTests":
             # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
             # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
             return True

        return False
   def       __a							(		self      :	Optional[int]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Any							=							MaMaaaModelTester(self							)
        UpperCAmelCase__						:    Optional[int]							=							ConfigTester(self							,			config_class=snake_case__							)
   def       __a							(		self      :	List[Any]							):


        '''simple docstring'''
        self.config_tester.run_common_tests()
   def       __a							(		self      :	Optional[Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							self.model_tester.prepare_config_and_inputs()
        for model_class in self.all_model_classes:
             UpperCAmelCase__						:    Dict							=							model_class(snake_case__							)

             with tempfile.TemporaryDirectory() as tmpdirname:
                  model.save_pretrained(snake_case__							)
                  UpperCAmelCase__						:    Dict							=							model_class.from_pretrained(snake_case__							,			output_loading_info=snake_case__							)
             self.assertEqual(info["missing_keys"]							,			[]							)
   def       __a							(		self      :	str							):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*snake_case__							)
   def       __a							(		self      :	Tuple							):


        '''simple docstring'''
        UpperCAmelCase__						:    Optional[Any]							=							self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_encoder_decoder_model_standalone(*snake_case__							)
   def       __a							(		self      :	Union[str, Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[Any]							=							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
             UpperCAmelCase__						:    Dict							=							model_class(snake_case__							)
             model.to(snake_case__							)
             model.eval()

             UpperCAmelCase__						:    Optional[Any]							=							copy.deepcopy(self._prepare_for_class(snake_case__							,			snake_case__							)							)

             if not self.is_encoder_decoder:
                  UpperCAmelCase__						:    Tuple							=							inputs['''input_ids''']
                  del inputs["input_ids"]
             else:
                  UpperCAmelCase__						:    Dict							=							inputs['''input_ids''']
                  UpperCAmelCase__						:    Union[str, Any]							=							inputs.get("decoder_input_ids"							,			snake_case__							)
                  del inputs["input_ids"]
                  inputs.pop("decoder_input_ids"							,			snake_case__							)

             UpperCAmelCase__						:    Dict							=							model.get_input_embeddings()
             if not self.is_encoder_decoder:
                  UpperCAmelCase__						:    str							=							wte(snake_case__							)
             else:
                  UpperCAmelCase__						:    Tuple							=							wte(snake_case__							)
                  UpperCAmelCase__						:    Union[str, Any]							=							wte(snake_case__							)

             with torch.no_grad():
                  model(**snake_case__							)[0]




   def       __a							(		self      :	Dict							):


        '''simple docstring'''
        UpperCAmelCase__						:    Dict							=							self.model_tester.prepare_config_and_inputs()
        UpperCAmelCase__						:    List[str]							=							input_dict['''input_ids''']
        UpperCAmelCase__						:    Union[str, Any]							=							input_ids.ne(1							).to(snake_case__							)
        UpperCAmelCase__						:    List[str]							=							MaMaaaForConditionalGeneration(snake_case__							).eval().to(snake_case__							)
        if torch_device == "cuda":
             model.half()
        model.generate(snake_case__							,			attention_mask=snake_case__							)
        model.generate(num_beams=4							,			do_sample=snake_case__							,			early_stopping=snake_case__							,			num_return_sequences=3							)




def 	SCREAMING_SNAKE_CASE__       (  snake_case       : List[Any]				)->		List[str]:






     '''simple docstring'''



     return torch.tensor(snake_case__			,					dtype=torch.long			,					device=snake_case__				)


_lowerCAmelCase	:	Any				=      1e-4




@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 			lowerCAmelCase__			(    unittest.TestCase   ):
   @cached_property
   def       __a							(		self      :	Optional[int]							):


        '''simple docstring'''
        return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"							)
   def       __a							(		self      :	List[Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							MaMaaaModel.from_pretrained("facebook/m2m100_418M"							).to(snake_case__							)
        UpperCAmelCase__						:    List[Any]							=							_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]							)
        UpperCAmelCase__						:    List[Any]							=							_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]							)
        UpperCAmelCase__						:    Tuple							=							prepare_mam_aaa_inputs_dict(model.config							,			snake_case__							,			snake_case__							)
        with torch.no_grad():
             UpperCAmelCase__						:    Optional[int]							=							model(**snake_case__							)[0]
        UpperCAmelCase__						:    Union[str, Any]							=							torch.Size((1, 1_1, 1_0_2_4)							)
        self.assertEqual(output.shape							,			snake_case__							)
        # change to expected output here
        UpperCAmelCase__						:    Tuple							=							torch.tensor(
            [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]							,			device=snake_case__							)
        self.assertTrue(torch.allclose(output[:, :3, :3]							,			snake_case__							,			atol=snake_case__							)							)
   def       __a							(		self      :	str							):


        '''simple docstring'''
        UpperCAmelCase__						:    str							=							MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"							).to(snake_case__							)

        # change to intended input
        UpperCAmelCase__						:    str							=							_long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]							)
        UpperCAmelCase__						:    Tuple							=							_long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]							)
        UpperCAmelCase__						:    str							=							prepare_mam_aaa_inputs_dict(model.config							,			snake_case__							,			snake_case__							)
        with torch.no_grad():
             UpperCAmelCase__						:    Tuple							=							model(**snake_case__							)[0]
        UpperCAmelCase__						:    List[str]							=							torch.Size((1, 1_1, model.config.vocab_size)							)
        self.assertEqual(output.shape							,			snake_case__							)
        # change to expected output here
        UpperCAmelCase__						:    List[str]							=							torch.tensor(
            [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]							,			device=snake_case__							)
        self.assertTrue(torch.allclose(output[:, :3, :3]							,			snake_case__							,			atol=snake_case__							)							)




   def       __a							(		self      :	str							):


        '''simple docstring'''
        UpperCAmelCase__						:    Any							=							MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"							).to(snake_case__							)
        UpperCAmelCase__						:    List[str]							=							MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"							,			src_lang="fr"							,			tgt_lang="en"							)

        UpperCAmelCase__						:    Optional[Any]							=							[
            '''L\'affaire NSA souligne l\'absence totale de débat sur le renseignement''',
            '''Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.''',
            '''Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent'''
            ''' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de'''
            ''' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.''',
        ]

        # The below article tests that we don't add any hypotheses outside of the top n_beams
        UpperCAmelCase__						:    Union[str, Any]							=							tokenizer(snake_case__							,			padding=snake_case__							,			return_tensors="pt"							)

        UpperCAmelCase__						:    int							=							model.generate(
            input_ids=dct["input_ids"].to(snake_case__							)							,			attention_mask=dct["attention_mask"].to(snake_case__							)							,			num_beams=5							,			forced_bos_token_id=tokenizer.get_lang_id("en"							)							,			)

        UpperCAmelCase__						:    Any							=							[
            '''The NSA case highlights the total absence of intelligence debate''',
            '''I think there are two levels of response from the French government.''',
            '''When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.'''
            ''' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all'''
            ''' communications in France.''',
        ]

        UpperCAmelCase__						:    int							=							tokenizer.batch_decode(
            hypotheses_batch.tolist()							,			clean_up_tokenization_spaces=snake_case__							,			skip_special_tokens=snake_case__							)
        assert generated == expected_en




'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np
      import tensorflow as tf

      from transformers import (
          TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          FlaubertConfig,
          TFFlaubertForMultipleChoice,
          TFFlaubertForQuestionAnsweringSimple,
          TFFlaubertForSequenceClassification,
          TFFlaubertForTokenClassification,
          TFFlaubertModel,
          TFFlaubertWithLMHeadModel,
      )





class 					A							:





     def __init__(				self		,     SCREAMING_SNAKE_CASE		,     )					->							Optional[Any]:






         """simple docstring"""






         A			:  List[str]   =		parent
         A			:  int   =		13
         A			:  Dict   =		7
         A			:  str   =		True
         A			:  Dict   =		True
         A			:  Tuple   =		True
         A			:  Union[str, Any]   =		True
         A			:  Dict   =		True
         A			:  str   =		False
         A			:  Union[str, Any]   =		False
         A			:  Union[str, Any]   =		False
         A			:  List[str]   =		2
         A			:  Optional[int]   =		99
         A			:  List[str]   =		0
         A			:  int   =		32
         A			:  Any   =		2
         A			:  Optional[Any]   =		4
         A			:  List[Any]   =		0.1
         A			:  List[str]   =		0.1
         A			:  Tuple   =		512
         A			:  Optional[Any]   =		16
         A			:  List[str]   =		2
         A			:  Tuple   =		0.02
         A			:  List[str]   =		3
         A			:  List[Any]   =		4
         A			:  Any   =		'''last'''
         A			:  int   =		True
         A			:  Union[str, Any]   =		None
         A			:  Dict   =		0





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  int   =		ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size      )
         A			:  Any   =		random_attention_mask([self.batch_size, self.seq_length]		,     dtype=tf.floataa      )

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

         A			:  Tuple   =		None
         if self.use_token_type_ids:
             A			:  Union[str, Any]   =		ids_tensor([self.batch_size, self.seq_length]		,     self.n_langs      )

         A			:  List[Any]   =		None
         A			:  List[Any]   =		None
         A			:  Tuple   =		None
         if self.use_labels:
             A			:  Dict   =		ids_tensor([self.batch_size]		,     self.type_sequence_label_size      )
             A			:  Dict   =		ids_tensor([self.batch_size, self.seq_length]		,     self.num_labels      )
             A			:  List[Any]   =		ids_tensor([self.batch_size]		,     2		,     dtype=tf.floataa      )
             A			:  Optional[Any]   =		ids_tensor([self.batch_size]		,     self.num_choices      )

         A			:  Dict   =		FlaubertConfig(
             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 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							List[str]:






         """simple docstring"""






         A			:  int   =		TFFlaubertModel(config=SCREAMING_SNAKE_CASE      )
         A			:  Optional[int]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
         A			:  int   =		model(SCREAMING_SNAKE_CASE      )

         A			:  List[str]   =		[input_ids, input_mask]
         A			:  str   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							List[str]:






         """simple docstring"""






         A			:  List[str]   =		TFFlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE      )

         A			:  Union[str, Any]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
         A			:  Tuple   =		model(SCREAMING_SNAKE_CASE      )

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





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Optional[Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		TFFlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE      )

         A			:  List[str]   =		{'''input_ids''': input_ids, '''lengths''': input_lengths}

         A			:  Tuple   =		model(SCREAMING_SNAKE_CASE      )

         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 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Any:






         """simple docstring"""






         A			:  Union[str, Any]   =		TFFlaubertForSequenceClassification(SCREAMING_SNAKE_CASE      )

         A			:  Dict   =		{'''input_ids''': input_ids, '''lengths''': input_lengths}

         A			:  Optional[Any]   =		model(SCREAMING_SNAKE_CASE      )

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





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							str:






         """simple docstring"""






         A			:  Optional[Any]   =		self.num_labels
         A			:  str   =		TFFlaubertForTokenClassification(config=SCREAMING_SNAKE_CASE      )
         A			:  List[str]   =		{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
         A			:  int   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.num_labels)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     )					->							Any:






         """simple docstring"""






         A			:  str   =		self.num_choices
         A			:  int   =		TFFlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE      )
         A			:  str   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  Optional[Any]   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  str   =		tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE		,     1      )		,     (1, self.num_choices, 1)      )
         A			:  List[str]   =		{
             '''input_ids''': multiple_choice_inputs_ids,
             '''attention_mask''': multiple_choice_input_mask,
             '''token_type_ids''': multiple_choice_token_type_ids,
         }
         A			:  List[Any]   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_choices)      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  Tuple   =		self.prepare_config_and_inputs()
         (
             (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    (
             A
         ),    
         )			:  Any   =		config_and_inputs
         A			:  List[str]   =		{
             '''input_ids''': input_ids,
             '''token_type_ids''': token_type_ids,
             '''langs''': token_type_ids,
             '''lengths''': input_lengths,
         }
         return config, inputs_dict





@require_tf
class 					A							(				__snake_case       ,     __snake_case       ,     unittest.TestCase		):
     __magic_name__          =						(
         (
             TFFlaubertModel,
             TFFlaubertWithLMHeadModel,
             TFFlaubertForSequenceClassification,
             TFFlaubertForQuestionAnsweringSimple,
             TFFlaubertForTokenClassification,
             TFFlaubertForMultipleChoice,
         )
         if is_tf_available()
         else ()
     )
     __magic_name__          =						(
         (TFFlaubertWithLMHeadModel,) if is_tf_available() else ()
     )  # TODO (PVP): Check other models whether language generation is also applicable
     __magic_name__          =						(
         {
             '''feature-extraction''': TFFlaubertModel,
             '''fill-mask''': TFFlaubertWithLMHeadModel,
             '''question-answering''': TFFlaubertForQuestionAnsweringSimple,
             '''text-classification''': TFFlaubertForSequenceClassification,
             '''token-classification''': TFFlaubertForTokenClassification,
             '''zero-shot''': TFFlaubertForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     __magic_name__          =						False
     __magic_name__          =						False





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							List[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 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  int   =		TFFlaubertModelTester(self      )
         A			:  Dict   =		ConfigTester(self		,     config_class=SCREAMING_SNAKE_CASE		,     emb_dim=37      )





     def 							__lowerCAmelCase				(				self      )					->							Optional[Any]:






         """simple docstring"""






         self.config_tester.run_common_tests()





     def 							__lowerCAmelCase				(				self      )					->							Optional[int]:






         """simple docstring"""






         A			:  List[Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         A			:  int   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Union[str, Any]:






         """simple docstring"""






         A			:  Optional[int]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  Tuple   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_for_token_classification(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A			:  str   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_flaubert_for_multiple_choice(*SCREAMING_SNAKE_CASE      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Union[str, Any]:






         """simple docstring"""






         for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A			:  Union[str, Any]   =		TFFlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE      )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE      )





@require_tf
@require_sentencepiece
@require_tokenizers
class 					A							(				unittest.TestCase		):





     @slow
     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         A			:  Tuple   =		TFFlaubertModel.from_pretrained('''jplu/tf-flaubert-small-cased'''      )

         A			:  List[str]   =		tf.convert_to_tensor(
             [[0, 158, 735, 2592, 1424, 6727, 82, 1]]		,     dtype=tf.intaa		,     )  # "J'aime flaubert !"

         A			:  int   =		model(SCREAMING_SNAKE_CASE      )[0]
         A			:  str   =		tf.TensorShape((1, 8, 512)      )
         self.assertEqual(output.shape		,     SCREAMING_SNAKE_CASE      )
         # compare the actual values for a slice.
         A			:  Union[str, Any]   =		tf.convert_to_tensor(
             [
                 [
                     [-1.8_768_773, -1.566_555, 0.27_072_418],
                     [-1.6_920_038, -0.5_873_505, 1.9_329_599],
                     [-2.9_563_985, -1.6_993_835, 1.7_972_052],
                 ]
             ]		,     dtype=tf.floataa		,     )

         self.assertTrue(np.allclose(output[:, :3, :3].numpy()		,     expected_slice.numpy()		,     atol=1e-4      )      )




