






"""simple docstring"""







import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     FlaubertForMultipleChoice,
     FlaubertForQuestionAnswering,
     FlaubertForQuestionAnsweringSimple,
     FlaubertForSequenceClassification,
     FlaubertForTokenClassification,
     FlaubertModel,
     FlaubertWithLMHeadModel,
 )
 from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST





class   UpperCamelCase_ (       a_  ):



  def __init__(      self ,		snake_case__ ,		snake_case__=13 ,		snake_case__=7 ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=True ,		snake_case__=False ,		snake_case__=False ,		snake_case__=False ,		snake_case__=2 ,		snake_case__=99 ,		snake_case__=0 ,		snake_case__=32 ,		snake_case__=5 ,		snake_case__=4 ,		snake_case__=0.1 ,		snake_case__=0.1 ,		snake_case__=5_12 ,		snake_case__=12 ,		snake_case__=2 ,		snake_case__=0.02 ,		snake_case__=3 ,		snake_case__=4 ,		snake_case__="last" ,		snake_case__=None ,		snake_case__=None ,		)			->			str:



      """simple docstring"""





      UpperCAmelCase	    =			parent
      UpperCAmelCase	    =			batch_size
      UpperCAmelCase	    =			seq_length
      UpperCAmelCase	    =			is_training
      UpperCAmelCase	    =			use_input_lengths
      UpperCAmelCase	    =			use_token_type_ids
      UpperCAmelCase	    =			use_labels
      UpperCAmelCase	    =			gelu_activation
      UpperCAmelCase	    =			sinusoidal_embeddings
      UpperCAmelCase	    =			causal
      UpperCAmelCase	    =			asm
      UpperCAmelCase	    =			n_langs
      UpperCAmelCase	    =			vocab_size
      UpperCAmelCase	    =			n_special
      UpperCAmelCase	    =			hidden_size
      UpperCAmelCase	    =			num_hidden_layers
      UpperCAmelCase	    =			num_attention_heads
      UpperCAmelCase	    =			hidden_dropout_prob
      UpperCAmelCase	    =			attention_probs_dropout_prob
      UpperCAmelCase	    =			max_position_embeddings
      UpperCAmelCase	    =			type_vocab_size
      UpperCAmelCase	    =			type_sequence_label_size
      UpperCAmelCase	    =			initializer_range
      UpperCAmelCase	    =			num_labels
      UpperCAmelCase	    =			num_choices
      UpperCAmelCase	    =			summary_type
      UpperCAmelCase	    =			use_proj
      UpperCAmelCase	    =			scope



  def 		UpperCamelCase_				(      self				)			->			int:



      """simple docstring"""





      UpperCAmelCase	    =			ids_tensor([self.batch_size, self.seq_length] ,		self.vocab_size				)
      UpperCAmelCase	    =			random_attention_mask([self.batch_size, self.seq_length]				)

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

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

      UpperCAmelCase	    =			None
      UpperCAmelCase	    =			None
      UpperCAmelCase	    =			None
      if self.use_labels:
          UpperCAmelCase	    =			ids_tensor([self.batch_size] ,		self.type_sequence_label_size				)
          UpperCAmelCase	    =			ids_tensor([self.batch_size, self.seq_length] ,		self.num_labels				)
          UpperCAmelCase	    =			ids_tensor([self.batch_size] ,		2				).float()
          UpperCAmelCase	    =			ids_tensor([self.batch_size] ,		self.num_choices				)

      UpperCAmelCase	    =			self.get_config()

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



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



      """simple docstring"""





      return 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 ,		)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			Any:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertModel(config=snake_case__				)
      model.to(snake_case__				)
      model.eval()
      UpperCAmelCase	    =			model(snake_case__ ,		lengths=snake_case__ ,		langs=snake_case__				)
      UpperCAmelCase	    =			model(snake_case__ ,		langs=snake_case__				)
      UpperCAmelCase	    =			model(snake_case__				)
      self.parent.assertEqual(result.last_hidden_state.shape ,		(self.batch_size, self.seq_length, self.hidden_size)				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			Optional[int]:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertWithLMHeadModel(snake_case__				)
      model.to(snake_case__				)
      model.eval()

      UpperCAmelCase	    =			model(snake_case__ ,		token_type_ids=snake_case__ ,		labels=snake_case__				)
      self.parent.assertEqual(result.loss.shape ,		()				)
      self.parent.assertEqual(result.logits.shape ,		(self.batch_size, self.seq_length, self.vocab_size)				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			Dict:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertForQuestionAnsweringSimple(snake_case__				)
      model.to(snake_case__				)
      model.eval()

      UpperCAmelCase	    =			model(snake_case__				)

      UpperCAmelCase	    =			model(snake_case__ ,		start_positions=snake_case__ ,		end_positions=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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			str:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertForQuestionAnswering(snake_case__				)
      model.to(snake_case__				)
      model.eval()

      UpperCAmelCase	    =			model(snake_case__				)

      UpperCAmelCase	    =			model(
          snake_case__ ,		start_positions=snake_case__ ,		end_positions=snake_case__ ,		cls_index=snake_case__ ,		is_impossible=snake_case__ ,		p_mask=snake_case__ ,		)

      UpperCAmelCase	    =			model(
          snake_case__ ,		start_positions=snake_case__ ,		end_positions=snake_case__ ,		cls_index=snake_case__ ,		is_impossible=snake_case__ ,		)

      ((UpperCAmelCase       )    ,              )	    =			result_with_labels.to_tuple()

      UpperCAmelCase	    =			model(snake_case__ ,		start_positions=snake_case__ ,		end_positions=snake_case__				)

      ((UpperCAmelCase       )    ,              )	    =			result_with_labels.to_tuple()

      self.parent.assertEqual(result_with_labels.loss.shape ,		()				)
      self.parent.assertEqual(result.start_top_log_probs.shape ,		(self.batch_size, model.config.start_n_top)				)
      self.parent.assertEqual(result.start_top_index.shape ,		(self.batch_size, model.config.start_n_top)				)
      self.parent.assertEqual(
          result.end_top_log_probs.shape ,		(self.batch_size, model.config.start_n_top * model.config.end_n_top)				)
      self.parent.assertEqual(
          result.end_top_index.shape ,		(self.batch_size, model.config.start_n_top * model.config.end_n_top)				)
      self.parent.assertEqual(result.cls_logits.shape ,		(self.batch_size,)				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			Any:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertForSequenceClassification(snake_case__				)
      model.to(snake_case__				)
      model.eval()

      UpperCAmelCase	    =			model(snake_case__				)
      UpperCAmelCase	    =			model(snake_case__ ,		labels=snake_case__				)

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



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			List[Any]:



      """simple docstring"""





      UpperCAmelCase	    =			self.num_labels
      UpperCAmelCase	    =			FlaubertForTokenClassification(snake_case__				)
      model.to(snake_case__				)
      model.eval()

      UpperCAmelCase	    =			model(snake_case__ ,		attention_mask=snake_case__ ,		labels=snake_case__				)
      self.parent.assertEqual(result.logits.shape ,		(self.batch_size, self.seq_length, self.num_labels)				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		)			->			List[str]:



      """simple docstring"""





      UpperCAmelCase	    =			self.num_choices
      UpperCAmelCase	    =			FlaubertForMultipleChoice(config=snake_case__				)
      model.to(snake_case__				)
      model.eval()
      UpperCAmelCase	    =			input_ids.unsqueeze(1				).expand(-1 ,		self.num_choices ,		-1				).contiguous()
      UpperCAmelCase	    =			token_type_ids.unsqueeze(1				).expand(-1 ,		self.num_choices ,		-1				).contiguous()
      UpperCAmelCase	    =			input_mask.unsqueeze(1				).expand(-1 ,		self.num_choices ,		-1				).contiguous()
      UpperCAmelCase	    =			model(
          snake_case__ ,		attention_mask=snake_case__ ,		token_type_ids=snake_case__ ,		labels=snake_case__ ,		)
      self.parent.assertEqual(result.logits.shape ,		(self.batch_size, self.num_choices)				)



  def 		UpperCamelCase_				(      self				)			->			Any:



      """simple docstring"""





      UpperCAmelCase	    =			self.prepare_config_and_inputs()
      (
          (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,       (
          UpperCAmelCase       
      )    ,              
      )	    =			config_and_inputs
      UpperCAmelCase	    =			{
          """input_ids""": input_ids,
          """token_type_ids""": token_type_ids,
          """lengths""": input_lengths,
          """attention_mask""": input_mask,
      }
      return config, inputs_dict





@require_torch
class   UpperCamelCase_ (       a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					Optional[int]				=	(
      (
          FlaubertModel,
          FlaubertWithLMHeadModel,
          FlaubertForQuestionAnswering,
          FlaubertForQuestionAnsweringSimple,
          FlaubertForSequenceClassification,
          FlaubertForTokenClassification,
          FlaubertForMultipleChoice,
      )
      if is_torch_available()
      else ()
  )
  _A       :					Union[str, Any]				=	(
      {
          'feature-extraction': FlaubertModel,
          'fill-mask': FlaubertWithLMHeadModel,
          'question-answering': FlaubertForQuestionAnsweringSimple,
          'text-classification': FlaubertForSequenceClassification,
          'token-classification': FlaubertForTokenClassification,
          'zero-shot': FlaubertForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__				)			->			str:



      """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 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__=False				)			->			Dict:



      """simple docstring"""





      UpperCAmelCase	    =			super()._prepare_for_class(snake_case__ ,		snake_case__ ,		return_labels=snake_case__				)

      if return_labels:
          if model_class.__name__ == "FlaubertForQuestionAnswering":
              UpperCAmelCase	    =			torch.zeros(
                  self.model_tester.batch_size ,		dtype=torch.long ,		device=snake_case__				)
              UpperCAmelCase	    =			torch.zeros(
                  self.model_tester.batch_size ,		dtype=torch.long ,		device=snake_case__				)

      return inputs_dict



  def 		UpperCamelCase_				(      self				)			->			str:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertModelTester(self				)
      UpperCAmelCase	    =			ConfigTester(self ,		config_class=snake_case__ ,		emb_dim=37				)



  def 		UpperCamelCase_				(      self				)			->			str:



      """simple docstring"""





      self.config_tester.run_common_tests()



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



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_model(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Any:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_lm_head(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Dict:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_simple_qa(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Dict:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_qa(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Tuple:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_sequence_classif(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			List[str]:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_token_classif(*snake_case__				)



  def 		UpperCamelCase_				(      self				)			->			Dict:



      """simple docstring"""





      UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_flaubert_multiple_choice(*snake_case__				)



  @slow
  def 		UpperCamelCase_				(      self				)			->			List[str]:



      """simple docstring"""





      for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          UpperCAmelCase	    =			FlaubertModel.from_pretrained(snake_case__				)
          self.assertIsNotNone(snake_case__				)



  @slow
  @require_torch_gpu
  def 		UpperCamelCase_				(      self				)			->			List[Any]:



      """simple docstring"""





      UpperCAmelCase    ,       UpperCAmelCase	    =			self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
          # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
          if model_class == FlaubertForMultipleChoice:
              return

          UpperCAmelCase	    =			True
          UpperCAmelCase	    =			model_class(config=snake_case__				)

          UpperCAmelCase	    =			self._prepare_for_class(snake_case__ ,		snake_case__				)
          UpperCAmelCase	    =			torch.jit.trace(
              snake_case__ ,		(inputs_dict["""input_ids"""].to("""cpu"""				), inputs_dict["""attention_mask"""].to("""cpu"""				))				)

          with tempfile.TemporaryDirectory() as tmp:
              torch.jit.save(snake_case__ ,		os.path.join(snake_case__ ,		"""traced_model.pt"""				)				)
              UpperCAmelCase	    =			torch.jit.load(os.path.join(snake_case__ ,		"""traced_model.pt"""				) ,		map_location=snake_case__				)
              loaded(inputs_dict["""input_ids"""].to(snake_case__				) ,		inputs_dict["""attention_mask"""].to(snake_case__				)				)





@require_torch
class   UpperCamelCase_ (       unittest.TestCase  ):



  @slow
  def 		UpperCamelCase_				(      self				)			->			Any:



      """simple docstring"""





      UpperCAmelCase	    =			FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased"""				)
      UpperCAmelCase	    =			torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]				)
      with torch.no_grad():
          UpperCAmelCase	    =			model(snake_case__				)[0]
      UpperCAmelCase	    =			torch.Size((1, 11, 7_68)				)
      self.assertEqual(output.shape ,		snake_case__				)
      UpperCAmelCase	    =			torch.tensor(
          [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]]				)

      self.assertTrue(torch.allclose(output[:, :3, :3] ,		snake_case__ ,		atol=1e-4				)				)








"""simple docstring"""







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCAmelCase_	:    int            =      logging.get_logger(__name__)

lowerCAmelCase_	:    List[Any]            =      {
    '''facebook/xlm-roberta-xl''': '''https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json''',
    '''facebook/xlm-roberta-xxl''': '''https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json''',
    # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl
}





class   UpperCamelCase_ (       a_  ):
  _A       :					int				=	'xlm-roberta-xl'



  def __init__(      self ,		snake_case__=25_08_80 ,		snake_case__=25_60 ,		snake_case__=36 ,		snake_case__=32 ,		snake_case__=1_02_40 ,		snake_case__="gelu" ,		snake_case__=0.1 ,		snake_case__=0.1 ,		snake_case__=5_14 ,		snake_case__=1 ,		snake_case__=0.02 ,		snake_case__=1e-05 ,		snake_case__=1 ,		snake_case__=0 ,		snake_case__=2 ,		snake_case__="absolute" ,		snake_case__=True ,		snake_case__=None ,		**snake_case__ ,		)			->			Union[str, Any]:



         """simple docstring"""





         super().__init__(pad_token_id=snake_case__ ,		bos_token_id=snake_case__ ,		eos_token_id=snake_case__ ,		**snake_case__				)
         UpperCAmelCase	    =			vocab_size
         UpperCAmelCase	    =			hidden_size
         UpperCAmelCase	    =			num_hidden_layers
         UpperCAmelCase	    =			num_attention_heads
         UpperCAmelCase	    =			hidden_act
         UpperCAmelCase	    =			intermediate_size
         UpperCAmelCase	    =			hidden_dropout_prob
         UpperCAmelCase	    =			attention_probs_dropout_prob
         UpperCAmelCase	    =			max_position_embeddings
         UpperCAmelCase	    =			type_vocab_size
         UpperCAmelCase	    =			initializer_range
         UpperCAmelCase	    =			layer_norm_eps
         UpperCAmelCase	    =			position_embedding_type
         UpperCAmelCase	    =			use_cache
         UpperCAmelCase	    =			classifier_dropout





class   UpperCamelCase_ (       a_  ):



  @property
  def 		UpperCamelCase_				(      self				)			->			Mapping[str, Mapping[int, str]]:



         """simple docstring"""





         if self.task == "multiple-choice":
                UpperCAmelCase	    =			{0: """batch""", 1: """choice""", 2: """sequence"""}
         else:
                UpperCAmelCase	    =			{0: """batch""", 1: """sequence"""}
         return OrderedDict(
             [
                 ("""input_ids""", dynamic_axis),
                 ("""attention_mask""", dynamic_axis),
             ]				)
