

'''simple docstring'''






from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

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


if is_tf_available():
 import tensorflow as tf

 from transformers import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor






class 			lowercase_	:




  """simple docstring"""




  def __init__(      self   :     Tuple					,lowercase__   :     Dict					,lowercase__   :     Optional[int]=1_3					,lowercase__   :     Any=3_0					,lowercase__   :     List[str]=2					,lowercase__   :     Optional[Any]=3					,lowercase__   :     Union[str, Any]=True					,lowercase__   :     Optional[Any]=True					,lowercase__   :     Optional[int]=3_2					,lowercase__   :     Dict=2					,lowercase__   :     Union[str, Any]=4					,lowercase__   :     Tuple=3_7					,lowercase__   :     List[Any]="gelu"					,lowercase__   :     Union[str, Any]=0.1					,lowercase__   :     Union[str, Any]=0.1					,lowercase__   :     int=1_0					,lowercase__   :     Optional[Any]=0.0_2					,lowercase__   :     Dict=3					,lowercase__   :     List[str]=0.6					,lowercase__   :     Any=None					,):
   __lowercase							  = parent
   __lowercase							  = batch_size
   __lowercase							  = image_size
   __lowercase							  = patch_size
   __lowercase							  = num_channels
   __lowercase							  = is_training
   __lowercase							  = use_labels
   __lowercase							  = hidden_size
   __lowercase							  = num_hidden_layers
   __lowercase							  = num_attention_heads
   __lowercase							  = intermediate_size
   __lowercase							  = hidden_act
   __lowercase							  = hidden_dropout_prob
   __lowercase							  = attention_probs_dropout_prob
   __lowercase							  = type_sequence_label_size
   __lowercase							  = initializer_range
   __lowercase							  = mask_ratio
   __lowercase							  = scope

   # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
   # (we add 1 for the [CLS] token)
   __lowercase							  = (image_size // patch_size) ** 2
   __lowercase							  = int(math.ceil((1 - mask_ratio) * (num_patches + 1)			)			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   __lowercase							  = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

   __lowercase							  = None
   if self.use_labels:
    __lowercase							  = ids_tensor([self.batch_size]					,self.type_sequence_label_size			)

   __lowercase							  = self.get_config()

   return config, pixel_values, labels






  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   return ViTMAEConfig(
       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					,decoder_hidden_size=self.hidden_size					,decoder_num_hidden_layers=self.num_hidden_layers					,decoder_num_attention_heads=self.num_attention_heads					,decoder_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=lowercase__					,initializer_range=self.initializer_range					,mask_ratio=self.mask_ratio					,)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]					,lowercase__   :     Any					,lowercase__   :     int					,lowercase__   :     Dict			):
   __lowercase							  = TFViTMAEModel(config=lowercase__			)
   __lowercase							  = model(lowercase__					,training=lowercase__			)
   self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, self.seq_length, self.hidden_size)			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Dict					,lowercase__   :     Tuple					,lowercase__   :     Dict					,lowercase__   :     Any			):
   __lowercase							  = TFViTMAEForPreTraining(lowercase__			)
   __lowercase							  = model(lowercase__					,training=lowercase__			)
   # expected sequence length = num_patches
   __lowercase							  = (self.image_size // self.patch_size) ** 2
   __lowercase							  = self.patch_size**2 * self.num_channels
   self.parent.assertEqual(result.logits.shape					,(self.batch_size, num_patches, expected_num_channels)			)

   # test greyscale images
   __lowercase							  = 1
   __lowercase							  = TFViTMAEForPreTraining(lowercase__			)

   __lowercase							  = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
   __lowercase							  = model(lowercase__					,training=lowercase__			)
   __lowercase							  = self.patch_size**2
   self.parent.assertEqual(result.logits.shape					,(self.batch_size, num_patches, expected_num_channels)			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   __lowercase							  = self.prepare_config_and_inputs()
   ((__lowercase)  ,	(__lowercase)  ,	(__lowercase))							  = config_and_inputs
   __lowercase							  = {'''pixel_values''': pixel_values}
   return config, inputs_dict






@require_tf
class 			lowercase_	(lowerCamelCase__				,       lowerCamelCase__				,       unittest.TestCase      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Optional[int]							=			(TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
  SCREAMING_SNAKE_CASE    :  Union[str, Any]							=			{'feature-extraction': TFViTMAEModel} if is_tf_available() else {}

  SCREAMING_SNAKE_CASE    :  Optional[Any]							=			False
  SCREAMING_SNAKE_CASE    :  Any							=			False
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			False
  SCREAMING_SNAKE_CASE    :  Tuple							=			False






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   __lowercase							  = TFViTMAEModelTester(self			)
   __lowercase							  = ConfigTester(self					,config_class=lowercase__					,has_text_modality=lowercase__					,hidden_size=3_7			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   self.config_tester.run_common_tests()






  @unittest.skip(reason='''ViTMAE does not use inputs_embeds'''			)
  def 					SCREAMING_SNAKE_CASE      (      self   :     int			):
   pass






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    __lowercase							  = model_class(lowercase__			)
    self.assertIsInstance(model.get_input_embeddings()					,(tf.keras.layers.Layer)			)
    __lowercase							  = model.get_output_embeddings()
    self.assertTrue(x is None or isinstance(lowercase__					,tf.keras.layers.Layer			)			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]			):
   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

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

    __lowercase							  = ['''pixel_values''']
    self.assertListEqual(arg_names[:1]					,lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_pretraining(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   # make the mask reproducible
   np.random.seed(2			)

   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   __lowercase							  = int((config.image_size // config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)

   for model_class in self.all_model_classes:
    __lowercase							  = model_class(lowercase__			)
    __lowercase							  = self._prepare_for_class(lowercase__					,lowercase__			)

    __lowercase							  = model(lowercase__					,noise=lowercase__			)

    __lowercase							  = copy.deepcopy(self._prepare_for_class(lowercase__					,lowercase__			)			)
    __lowercase							  = model(**lowercase__					,noise=lowercase__			)
    __lowercase							  = outputs_dict[0].numpy()
    __lowercase							  = outputs_keywords[0].numpy()

    self.assertLess(np.sum(np.abs(output_dict - output_keywords			)			)					,1e-6			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     int			):
   # make the mask reproducible
   np.random.seed(2			)

   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   __lowercase							  = int((config.image_size // config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)

   def prepare_numpy_arrays(lowercase__   :     Dict			):
    __lowercase							  = {}
    for k, v in inputs_dict.items():
     if tf.is_tensor(lowercase__			):
      __lowercase							  = v.numpy()
     else:
      __lowercase							  = np.array(lowercase__			)

    return inputs_np_dict

   for model_class in self.all_model_classes:
    __lowercase							  = model_class(lowercase__			)

    __lowercase							  = self._prepare_for_class(lowercase__					,lowercase__			)
    __lowercase							  = prepare_numpy_arrays(lowercase__			)

    __lowercase							  = model(lowercase__					,noise=lowercase__			)
    __lowercase							  = model(**lowercase__					,noise=lowercase__			)
    self.assert_outputs_same(lowercase__					,lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     int					,lowercase__   :     Tuple					,lowercase__   :     Any			):
   # make masks reproducible
   np.random.seed(2			)

   __lowercase							  = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)
   __lowercase							  = tf.constant(lowercase__			)

   # Add `noise` argument.
   # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
   __lowercase							  = tf_noise

   super().check_pt_tf_models(lowercase__					,lowercase__					,lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   # make mask reproducible
   np.random.seed(2			)

   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   __lowercase							  = {
       module_member
       for model_class in self.all_model_classes
       for module in (import_module(model_class.__module__			),)
       for module_member_name in dir(lowercase__			)
       if module_member_name.endswith('''MainLayer'''			)
       # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
       and module_member_name[: -len('''MainLayer'''			)] == model_class.__name__[: -len('''Model'''			)]
       for module_member in (getattr(lowercase__					,lowercase__			),)
       if isinstance(lowercase__					,lowercase__			)
       and tf.keras.layers.Layer in module_member.__bases__
       and getattr(lowercase__					,'''_keras_serializable'''					,lowercase__			)
   }

   __lowercase							  = int((config.image_size // config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)
   __lowercase							  = tf.convert_to_tensor(lowercase__			)
   inputs_dict.update({'''noise''': noise}			)

   for main_layer_class in tf_main_layer_classes:
    __lowercase							  = main_layer_class(lowercase__			)

    __lowercase							  = {
        name: tf.keras.Input(tensor.shape[1:]					,dtype=tensor.dtype			) for name, tensor in inputs_dict.items()
    }

    __lowercase							  = tf.keras.Model(lowercase__					,outputs=main_layer(lowercase__			)			)
    __lowercase							  = model(lowercase__			)

    with tempfile.TemporaryDirectory() as tmpdirname:
     __lowercase							  = os.path.join(lowercase__					,'''keras_model.h5'''			)
     model.save(lowercase__			)
     __lowercase							  = tf.keras.models.load_model(
         lowercase__					,custom_objects={main_layer_class.__name__: main_layer_class}			)
     assert isinstance(lowercase__					,tf.keras.Model			)
     __lowercase							  = model(lowercase__			)
     self.assert_outputs_same(lowercase__					,lowercase__			)






  @slow
  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   # make mask reproducible
   np.random.seed(2			)

   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   __lowercase							  = int((config.image_size // config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)

   for model_class in self.all_model_classes:
    __lowercase							  = model_class(lowercase__			)
    __lowercase							  = self._prepare_for_class(lowercase__					,lowercase__			)
    __lowercase							  = model(lowercase__					,noise=lowercase__			)

    if model_class.__name__ == "TFViTMAEModel":
     __lowercase							  = outputs.last_hidden_state.numpy()
     __lowercase							  = 0
    else:
     __lowercase							  = outputs.logits.numpy()
     __lowercase							  = 0

    with tempfile.TemporaryDirectory() as tmpdirname:
     model.save_pretrained(lowercase__					,saved_model=lowercase__			)
     __lowercase							  = model_class.from_pretrained(lowercase__			)
     __lowercase							  = model(lowercase__					,noise=lowercase__			)

     if model_class.__name__ == "TFViTMAEModel":
      __lowercase							  = after_outputs['''last_hidden_state'''].numpy()
      __lowercase							  = 0
     else:
      __lowercase							  = after_outputs['''logits'''].numpy()
      __lowercase							  = 0

     __lowercase							  = np.amax(np.abs(out_a - out_a			)			)
     self.assertLessEqual(lowercase__					,1e-5			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[Any]			):
   # make mask reproducible
   np.random.seed(2			)

   __lowercase  ,	__lowercase							  = self.model_tester.prepare_config_and_inputs_for_common()

   __lowercase							  = int((config.image_size // config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)

   for model_class in self.all_model_classes:
    __lowercase							  = model_class(lowercase__			)
    __lowercase							  = self._prepare_for_class(lowercase__					,lowercase__			)

    __lowercase							  = model(lowercase__					,noise=lowercase__			)
    __lowercase							  = model.get_config()
    # make sure that returned config is jsonifiable, which is required by keras
    json.dumps(lowercase__			)
    __lowercase							  = model_class.from_config(model.get_config()			)
    # make sure it also accepts a normal config
    __lowercase							  = model_class.from_config(model.config			)
    __lowercase							  = new_model(lowercase__			)  # Build model
    new_model.set_weights(model.get_weights()			)
    __lowercase							  = new_model(lowercase__					,noise=lowercase__			)

    self.assert_outputs_same(lowercase__					,lowercase__			)






  @unittest.skip(
      reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''			)
  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   pass






  @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'''			)
  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   pass






  @slow
  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]			):
   __lowercase							  = TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224'''			)
   self.assertIsNotNone(lowercase__			)


def 		_A     (    ):






 """simple docstring"""



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






@require_tf
@require_vision
class 			lowercase_	(unittest.TestCase      ):




  """simple docstring"""




  @cached_property
  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base'''			) if is_vision_available() else None






  @slow
  def 					SCREAMING_SNAKE_CASE      (      self   :     Any			):
   # make random mask reproducible across the PT and TF model
   np.random.seed(2			)

   __lowercase							  = TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base'''			)

   __lowercase							  = self.default_image_processor
   __lowercase							  = prepare_img()
   __lowercase							  = image_processor(images=lowercase__					,return_tensors='''tf'''			)

   # prepare a noise vector that will be also used for testing the TF model
   # (this way we can ensure that the PT and TF models operate on the same inputs)
   __lowercase							  = ViTMAEConfig()
   __lowercase							  = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2			)
   __lowercase							  = np.random.uniform(size=(1, num_patches)			)

   # forward pass
   __lowercase							  = model(**lowercase__					,noise=lowercase__			)

   # verify the logits
   __lowercase							  = tf.convert_to_tensor([1, 1_9_6, 7_6_8]			)
   self.assertEqual(outputs.logits.shape					,lowercase__			)

   __lowercase							  = tf.convert_to_tensor(
       [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]]			)

   tf.debugging.assert_near(outputs.logits[0, :3, :3]					,lowercase__					,atol=1e-4			)




'''simple docstring'''






import unittest

from transformers import DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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 (
     DebertaForMaskedLM,
     DebertaForQuestionAnswering,
     DebertaForSequenceClassification,
     DebertaForTokenClassification,
     DebertaModel,
 )
 from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  def __init__(      self   :     Optional[Any]					,lowercase__   :     Optional[Any]					,lowercase__   :     Optional[int]=1_3					,lowercase__   :     Any=7					,lowercase__   :     Union[str, Any]=True					,lowercase__   :     Optional[int]=True					,lowercase__   :     List[str]=True					,lowercase__   :     str=True					,lowercase__   :     Dict=9_9					,lowercase__   :     Union[str, Any]=3_2					,lowercase__   :     List[str]=5					,lowercase__   :     int=4					,lowercase__   :     Dict=3_7					,lowercase__   :     Union[str, Any]="gelu"					,lowercase__   :     str=0.1					,lowercase__   :     List[str]=0.1					,lowercase__   :     Any=5_1_2					,lowercase__   :     Optional[int]=1_6					,lowercase__   :     Optional[int]=2					,lowercase__   :     Optional[int]=0.0_2					,lowercase__   :     Dict=False					,lowercase__   :     Optional[int]=True					,lowercase__   :     str="None"					,lowercase__   :     Optional[int]=3					,lowercase__   :     List[Any]=4					,lowercase__   :     Union[str, Any]=None					,):
   __lowercase							  = parent
   __lowercase							  = batch_size
   __lowercase							  = seq_length
   __lowercase							  = is_training
   __lowercase							  = use_input_mask
   __lowercase							  = use_token_type_ids
   __lowercase							  = use_labels
   __lowercase							  = vocab_size
   __lowercase							  = hidden_size
   __lowercase							  = num_hidden_layers
   __lowercase							  = num_attention_heads
   __lowercase							  = intermediate_size
   __lowercase							  = hidden_act
   __lowercase							  = hidden_dropout_prob
   __lowercase							  = attention_probs_dropout_prob
   __lowercase							  = max_position_embeddings
   __lowercase							  = type_vocab_size
   __lowercase							  = type_sequence_label_size
   __lowercase							  = initializer_range
   __lowercase							  = num_labels
   __lowercase							  = num_choices
   __lowercase							  = relative_attention
   __lowercase							  = position_biased_input
   __lowercase							  = pos_att_type
   __lowercase							  = scope






  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple			):
   __lowercase							  = ids_tensor([self.batch_size, self.seq_length]					,self.vocab_size			)

   __lowercase							  = None
   if self.use_input_mask:
    __lowercase							  = ids_tensor([self.batch_size, self.seq_length]					,vocab_size=2			)

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

   __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]					,self.num_choices			)

   __lowercase							  = self.get_config()

   return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[Any]			):
   return DebertaConfig(
       vocab_size=self.vocab_size					,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					,max_position_embeddings=self.max_position_embeddings					,type_vocab_size=self.type_vocab_size					,initializer_range=self.initializer_range					,relative_attention=self.relative_attention					,position_biased_input=self.position_biased_input					,pos_att_type=self.pos_att_type					,)






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   __lowercase							  = self.get_config()
   __lowercase							  = 3_0_0
   return config






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     Optional[Any]			):
   self.parent.assertListEqual(list(result.loss.size()			)					,[]			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     List[Any]					,lowercase__   :     Dict					,lowercase__   :     List[Any]					,lowercase__   :     Tuple					,lowercase__   :     Dict					,lowercase__   :     str					,lowercase__   :     Union[str, Any]			):
   __lowercase							  = DebertaModel(config=lowercase__			)
   model.to(lowercase__			)
   model.eval()
   __lowercase							  = model(lowercase__					,attention_mask=lowercase__					,token_type_ids=lowercase__			)[0]
   __lowercase							  = model(lowercase__					,token_type_ids=lowercase__			)[0]
   __lowercase							  = model(lowercase__			)[0]

   self.parent.assertListEqual(list(sequence_output.size()			)					,[self.batch_size, self.seq_length, self.hidden_size]			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple					,lowercase__   :     str					,lowercase__   :     Tuple					,lowercase__   :     Optional[Any]					,lowercase__   :     Dict					,lowercase__   :     int					,lowercase__   :     Tuple					,lowercase__   :     int			):
   __lowercase							  = DebertaForMaskedLM(config=lowercase__			)
   model.to(lowercase__			)
   model.eval()
   __lowercase							  = model(lowercase__					,attention_mask=lowercase__					,token_type_ids=lowercase__					,labels=lowercase__			)

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






  def 					SCREAMING_SNAKE_CASE      (      self   :     int					,lowercase__   :     Optional[int]					,lowercase__   :     Optional[int]					,lowercase__   :     int					,lowercase__   :     Union[str, Any]					,lowercase__   :     Dict					,lowercase__   :     List[Any]					,lowercase__   :     Optional[Any]			):
   __lowercase							  = self.num_labels
   __lowercase							  = DebertaForSequenceClassification(lowercase__			)
   model.to(lowercase__			)
   model.eval()
   __lowercase							  = model(lowercase__					,attention_mask=lowercase__					,token_type_ids=lowercase__					,labels=lowercase__			)
   self.parent.assertListEqual(list(result.logits.size()			)					,[self.batch_size, self.num_labels]			)
   self.check_loss_output(lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     Optional[int]					,lowercase__   :     Optional[int]					,lowercase__   :     Optional[int]					,lowercase__   :     Tuple					,lowercase__   :     List[str]					,lowercase__   :     List[str]					,lowercase__   :     Optional[int]			):
   __lowercase							  = self.num_labels
   __lowercase							  = DebertaForTokenClassification(config=lowercase__			)
   model.to(lowercase__			)
   model.eval()
   __lowercase							  = model(lowercase__					,attention_mask=lowercase__					,token_type_ids=lowercase__					,labels=lowercase__			)
   self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.seq_length, self.num_labels)			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any					,lowercase__   :     Any					,lowercase__   :     Any					,lowercase__   :     Dict					,lowercase__   :     Any					,lowercase__   :     Optional[Any]					,lowercase__   :     int					,lowercase__   :     List[str]			):
   __lowercase							  = DebertaForQuestionAnswering(config=lowercase__			)
   model.to(lowercase__			)
   model.eval()
   __lowercase							  = model(
       lowercase__					,attention_mask=lowercase__					,token_type_ids=lowercase__					,start_positions=lowercase__					,end_positions=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 					SCREAMING_SNAKE_CASE      (      self   :     Dict			):
   __lowercase							  = self.prepare_config_and_inputs()
   (
       (
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	(
       __lowercase
   )  ,	
   )							  = config_and_inputs
   __lowercase							  = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
   return config, inputs_dict






@require_torch
class 			lowercase_	(lowerCamelCase__				,       lowerCamelCase__				,       unittest.TestCase      ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Tuple							=			(
      (
          DebertaModel,
          DebertaForMaskedLM,
          DebertaForSequenceClassification,
          DebertaForTokenClassification,
          DebertaForQuestionAnswering,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE    :  Union[str, Any]							=			(
      {
          'feature-extraction': DebertaModel,
          'fill-mask': DebertaForMaskedLM,
          'question-answering': DebertaForQuestionAnswering,
          'text-classification': DebertaForSequenceClassification,
          'token-classification': DebertaForTokenClassification,
          'zero-shot': DebertaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE    :  Tuple							=			True
  SCREAMING_SNAKE_CASE    :  List[str]							=			False
  SCREAMING_SNAKE_CASE    :  List[str]							=			False
  SCREAMING_SNAKE_CASE    :  Any							=			False
  SCREAMING_SNAKE_CASE    :  List[Any]							=			False






  def 					SCREAMING_SNAKE_CASE      (      self   :     int			):
   __lowercase							  = DebertaModelTester(self			)
   __lowercase							  = ConfigTester(self					,config_class=lowercase__					,hidden_size=3_7			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     int			):
   self.config_tester.run_common_tests()






  def 					SCREAMING_SNAKE_CASE      (      self   :     List[str]			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_deberta_model(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_deberta_for_sequence_classification(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Dict			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_deberta_for_masked_lm(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_deberta_for_question_answering(*lowercase__			)






  def 					SCREAMING_SNAKE_CASE      (      self   :     Dict			):
   __lowercase							  = self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_deberta_for_token_classification(*lowercase__			)






  @slow
  def 					SCREAMING_SNAKE_CASE      (      self   :     Tuple			):
   for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __lowercase							  = DebertaModel.from_pretrained(lowercase__			)
    self.assertIsNotNone(lowercase__			)






@require_torch
@require_sentencepiece
@require_tokenizers
class 			lowercase_	(unittest.TestCase      ):




  """simple docstring"""




  @unittest.skip(reason='''Model not available yet'''			)
  def 					SCREAMING_SNAKE_CASE      (      self   :     str			):
   pass






  @slow
  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]			):
   __lowercase							  = DebertaModel.from_pretrained('''microsoft/deberta-base'''			)

   __lowercase							  = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]			)
   __lowercase							  = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]			)
   with torch.no_grad():
    __lowercase							  = model(lowercase__					,attention_mask=lowercase__			)[0]
   # compare the actual values for a slice.
   __lowercase							  = torch.tensor(
       [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]]			)
   self.assertTrue(torch.allclose(output[:, 1:4, 1:4]					,lowercase__					,atol=1e-4			)					,F"{output[:, 1:4, 1:4]}"			)

