





import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        MODEL_MAPPING,
        DataaVecVisionForImageClassification,
        DataaVecVisionForSemanticSegmentation,
        DataaVecVisionModel,
    )
    from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import BeitImageProcessor







class 		_lowerCAmelCase:

  """simple docstring"""







  def __init__(   self    ,							UpperCAmelCase    ,							UpperCAmelCase=1_00    ,							UpperCAmelCase=13    ,							UpperCAmelCase=30    ,							UpperCAmelCase=2    ,							UpperCAmelCase=3    ,							UpperCAmelCase=True    ,							UpperCAmelCase=True    ,							UpperCAmelCase=32    ,							UpperCAmelCase=4    ,							UpperCAmelCase=4    ,							UpperCAmelCase=37    ,							UpperCAmelCase="gelu"    ,							UpperCAmelCase=0.1    ,							UpperCAmelCase=0.1    ,							UpperCAmelCase=10    ,							UpperCAmelCase=0.02    ,							UpperCAmelCase=3    ,							UpperCAmelCase=None    ,							UpperCAmelCase=[0, 1, 2, 3]    ,							)->   Union[str, Any]:
     __A    =  parent
     __A    =  1_00
     __A    =  batch_size
     __A    =  image_size
     __A    =  patch_size
     __A    =  num_channels
     __A    =  is_training
     __A    =  use_labels
     __A    =  hidden_size
     __A    =  num_hidden_layers
     __A    =  num_attention_heads
     __A    =  intermediate_size
     __A    =  hidden_act
     __A    =  hidden_dropout_prob
     __A    =  attention_probs_dropout_prob
     __A    =  type_sequence_label_size
     __A    =  initializer_range
     __A    =  scope
     __A    =  out_indices
     __A    =  num_labels

     # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
     __A    =  (image_size // patch_size) ** 2
     __A    =  num_patches + 1

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Tuple:
     __A    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

     __A    =  None
     __A    =  None
     if self.use_labels:
        __A    =  ids_tensor([self.batch_size]    ,							self.type_sequence_label_size      )
        __A    =  ids_tensor([self.batch_size, self.image_size, self.image_size]    ,							self.num_labels      )

     __A    =  self.get_config()

     return config, pixel_values, labels, pixel_labels

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Tuple:
     return DataaVecVisionConfig(
         vocab_size=self.vocab_size    ,							image_size=self.image_size    ,							patch_size=self.patch_size    ,							num_channels=self.num_channels    ,							hidden_size=self.hidden_size    ,							num_hidden_layers=self.num_hidden_layers    ,							num_attention_heads=self.num_attention_heads    ,							intermediate_size=self.intermediate_size    ,							hidden_act=self.hidden_act    ,							hidden_dropout_prob=self.hidden_dropout_prob    ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,							is_decoder=UpperCAmelCase    ,							initializer_range=self.initializer_range    ,							out_indices=self.out_indices    ,							)

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Dict:
     __A    =  DataaVecVisionModel(config=UpperCAmelCase      )
     model.to(UpperCAmelCase      )
     model.eval()
     __A    =  model(UpperCAmelCase      )
     # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
     __A    =  (self.image_size // self.patch_size) ** 2
     self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, num_patches + 1, self.hidden_size)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Union[str, Any]:
     __A    =  self.type_sequence_label_size
     __A    =  DataaVecVisionForImageClassification(UpperCAmelCase      )
     model.to(UpperCAmelCase      )
     model.eval()
     __A    =  model(UpperCAmelCase    ,							labels=UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.type_sequence_label_size)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   List[str]:
     __A    =  self.num_labels
     __A    =  DataaVecVisionForSemanticSegmentation(UpperCAmelCase      )
     model.to(UpperCAmelCase      )
     model.eval()
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(
         result.logits.shape    ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
     __A    =  model(UpperCAmelCase    ,							labels=UpperCAmelCase      )
     self.parent.assertEqual(
         result.logits.shape    ,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     __A    =  self.prepare_config_and_inputs()
     __A   ,		__A   ,		__A   ,		__A    =  config_and_inputs
     __A    =  {'''pixel_values''': pixel_values}
     return config, inputs_dict







@require_torch
class 		_lowerCAmelCase(		_a						,       _a						,       unittest.TestCase):

  """simple docstring"""







  lowerCamelCase__     	=       (
      (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  lowerCamelCase__     	=       (
      {
          '''feature-extraction''': DataaVecVisionModel,
          '''image-classification''': DataaVecVisionForImageClassification,
          '''image-segmentation''': DataaVecVisionForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  lowerCamelCase__     	=       False
  lowerCamelCase__     	=       False
  lowerCamelCase__     	=       False

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     __A    =  DataaVecVisionModelTester(self      )
     __A    =  ConfigTester(
         self    ,							config_class=UpperCAmelCase    ,							has_text_modality=UpperCAmelCase    ,							hidden_size=37      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     self.config_tester.run_common_tests()

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     # Data2VecVision does not use inputs_embeds
     pass

  @require_torch_multi_gpu
  @unittest.skip(
      reason='''Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'''      )
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     pass

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A   ,		__A    =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __A    =  model_class(UpperCAmelCase      )
        self.assertIsInstance(model.get_input_embeddings()    ,							(nn.Module)      )
        __A    =  model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(UpperCAmelCase    ,							nn.Linear      )      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     __A   ,		__A    =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __A    =  model_class(UpperCAmelCase      )
        __A    =  inspect.signature(model.forward      )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        __A    =  [*signature.parameters.keys()]

        __A    =  ['''pixel_values''']
        self.assertListEqual(arg_names[:1]    ,							UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_segmentation(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     if not self.model_tester.is_training:
        return

     __A   ,		__A    =  self.model_tester.prepare_config_and_inputs_for_common()
     __A    =  True

     for model_class in self.all_model_classes:
        if model_class in [*get_values(UpperCAmelCase      )]:
           continue

        __A    =  model_class(UpperCAmelCase      )
        model.to(UpperCAmelCase      )
        model.train()
        __A    =  self._prepare_for_class(UpperCAmelCase    ,							UpperCAmelCase    ,							return_labels=UpperCAmelCase      )
        __A    =  model(**UpperCAmelCase      ).loss
        loss.backward()

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A   ,		__A    =  self.model_tester.prepare_config_and_inputs_for_common()
     if not self.model_tester.is_training:
        return

     __A    =  False
     __A    =  True

     for model_class in self.all_model_classes:
        if model_class in [*get_values(UpperCAmelCase      )] or not model_class.supports_gradient_checkpointing:
           continue
        # TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
        # this can then be incorporated into _prepare_for_class in test_modeling_common.py
        elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
           __A   ,		__A   ,		__A   ,		__A    =  inputs_dict['''pixel_values'''].shape
           __A    =  torch.zeros(
               [self.model_tester.batch_size, height, width]    ,							device=UpperCAmelCase      ).long()
        __A    =  model_class(UpperCAmelCase      )
        model.gradient_checkpointing_enable()
        model.to(UpperCAmelCase      )
        model.train()
        __A    =  self._prepare_for_class(UpperCAmelCase    ,							UpperCAmelCase    ,							return_labels=UpperCAmelCase      )
        __A    =  model(**UpperCAmelCase      ).loss
        loss.backward()

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Tuple:
     __A   ,		__A    =  self.model_tester.prepare_config_and_inputs_for_common()

     __A    =  _config_zero_init(UpperCAmelCase      )
     for model_class in self.all_model_classes:
        __A    =  model_class(config=UpperCAmelCase      )
        for name, param in model.named_parameters():
           # we skip lambda parameters as these require special initial values
           # determined by config.layer_scale_init_value
           if "lambda" in name:
              continue
           if param.requires_grad:
              self.assertIn(
                  ((param.data.mean() * 1e9).round() / 1e9).item()    ,							[0.0, 1.0]    ,							msg=f"Parameter {name} of model {model_class} seems not properly initialized"    ,							)

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase=2e-4    ,							UpperCAmelCase="outputs"    ,							UpperCAmelCase=None      )->   Optional[Any]:
     # We override with a slightly higher tol value, as semseg models tend to diverge a bit more
     super().check_pt_tf_outputs(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Dict:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase      )





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __A    =  DataaVecVisionModel.from_pretrained(UpperCAmelCase      )
        self.assertIsNotNone(UpperCAmelCase      )
def  __UpperCamelCase    (						)    ->		str:


   '''simple docstring'''







   __A    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
   return image







@require_torch
@require_vision
class 		_lowerCAmelCase(		unittest.TestCase):

  """simple docstring"""







  @cached_property
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Dict:
     return (
         BeitImageProcessor.from_pretrained('''facebook/data2vec-vision-base-ft1k'''      ) if is_vision_available() else None
     )





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     __A    =  DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''      ).to(
         UpperCAmelCase      )

     __A    =  self.default_image_processor
     __A    =  prepare_img()
     __A    =  image_processor(images=UpperCAmelCase    ,							return_tensors='''pt'''      ).to(UpperCAmelCase      )

     # forward pass
     with torch.no_grad():
        __A    =  model(**UpperCAmelCase      )
     __A    =  outputs.logits

     # verify the logits
     __A    =  torch.Size((1, 10_00)      )
     self.assertEqual(logits.shape    ,							UpperCAmelCase      )

     __A    =  torch.tensor([0.3277, -0.1395, 0.0911]      ).to(UpperCAmelCase      )

     self.assertTrue(torch.allclose(logits[0, :3]    ,							UpperCAmelCase    ,							atol=1e-4      )      )

     __A    =  [model.config.labelaid[i] for i in ['''remote control, remote''', '''tabby, tabby cat''']]
     self.assertEqual(logits[0].topk(2      ).indices.cpu().tolist()    ,							UpperCAmelCase      )








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:

  """simple docstring"""







  def __init__(   self    ,							UpperCAmelCase    ,							)->   List[Any]:
     __A    =  parent
     __A    =  13
     __A    =  7
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  False
     __A    =  False
     __A    =  False
     __A    =  2
     __A    =  99
     __A    =  0
     __A    =  32
     __A    =  2
     __A    =  4
     __A    =  0.1
     __A    =  0.1
     __A    =  5_12
     __A    =  16
     __A    =  2
     __A    =  0.02
     __A    =  3
     __A    =  4
     __A    =  '''last'''
     __A    =  True
     __A    =  None
     __A    =  0

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  ids_tensor([self.batch_size, self.seq_length]    ,							self.vocab_size      )
     __A    =  random_attention_mask([self.batch_size, self.seq_length]    ,							dtype=tf.floataa      )

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

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

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

     __A    =  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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Optional[Any]:
     __A    =  TFXLMModel(config=UpperCAmelCase      )
     __A    =  {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
     __A    =  model(UpperCAmelCase      )

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

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Tuple:
     __A    =  TFXLMWithLMHeadModel(UpperCAmelCase      )

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

     __A    =  outputs

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

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Dict:
     __A    =  TFXLMForQuestionAnsweringSimple(UpperCAmelCase      )

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

     __A    =  model(UpperCAmelCase      )

     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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Union[str, Any]:
     __A    =  TFXLMForSequenceClassification(UpperCAmelCase      )

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

     __A    =  model(UpperCAmelCase      )

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

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Tuple:
     __A    =  self.num_labels
     __A    =  TFXLMForTokenClassification(config=UpperCAmelCase      )
     __A    =  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.num_labels)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Union[str, Any]:
     __A    =  self.num_choices
     __A    =  TFXLMForMultipleChoice(config=UpperCAmelCase      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  {
         '''input_ids''': multiple_choice_inputs_ids,
         '''attention_mask''': multiple_choice_input_mask,
         '''token_type_ids''': multiple_choice_token_type_ids,
     }
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_choices)      )





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  self.prepare_config_and_inputs()
     (
         (
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		
     )    =  config_and_inputs
     __A    =  {
         '''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):

  """simple docstring"""







  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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   List[Any]:
     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 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  TFXLMModelTester(self      )
     __A    =  ConfigTester(self    ,							config_class=UpperCAmelCase    ,							emb_dim=37      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     self.config_tester.run_common_tests()

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_model(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_lm_head(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[Any]:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_qa(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_sequence_classif(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Tuple:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_for_token_classification(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCAmelCase      )





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __A    =  TFXLMModel.from_pretrained(UpperCAmelCase      )
        self.assertIsNotNone(UpperCAmelCase      )







@require_tf
class 		_lowerCAmelCase(		unittest.TestCase):

  """simple docstring"""







  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  TFXLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048'''      )
     __A    =  tf.convert_to_tensor([[14, 4_47]]    ,							dtype=tf.intaa      )  # the president
     __A    =  [
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
     ]  # 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
     __A    =  model.generate(UpperCAmelCase    ,							do_sample=UpperCAmelCase      )
     self.assertListEqual(output_ids[0].numpy().tolist()    ,							UpperCAmelCase      )

