


import unittest

from transformers import DebertaVaConfig, 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 (
        DebertaVaForMaskedLM,
        DebertaVaForMultipleChoice,
        DebertaVaForQuestionAnswering,
        DebertaVaForSequenceClassification,
        DebertaVaForTokenClassification,
        DebertaVaModel,
    )
    from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST



class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   def __init__(  self  : str       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : int=1_3       ,  _lowerCamelCase  : Any=7       ,  _lowerCamelCase  : List[Any]=True       ,  _lowerCamelCase  : Optional[int]=True       ,  _lowerCamelCase  : Optional[Any]=True       ,  _lowerCamelCase  : str=True       ,  _lowerCamelCase  : Tuple=9_9       ,  _lowerCamelCase  : List[str]=3_2       ,  _lowerCamelCase  : Tuple=5       ,  _lowerCamelCase  : List[Any]=4       ,  _lowerCamelCase  : Optional[int]=3_7       ,  _lowerCamelCase  : str="gelu"       ,  _lowerCamelCase  : Union[str, Any]=0.1       ,  _lowerCamelCase  : Union[str, Any]=0.1       ,  _lowerCamelCase  : int=5_1_2       ,  _lowerCamelCase  : List[str]=1_6       ,  _lowerCamelCase  : str=2       ,  _lowerCamelCase  : int=0.02       ,  _lowerCamelCase  : int=False       ,  _lowerCamelCase  : Optional[int]=True       ,  _lowerCamelCase  : str="None"       ,  _lowerCamelCase  : Optional[int]=3       ,  _lowerCamelCase  : Dict=4       ,  _lowerCamelCase  : Optional[int]=None       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						parent
         __lowerCamelCase     :      List[Any]       						=						batch_size
         __lowerCamelCase     :      Tuple       						=						seq_length
         __lowerCamelCase     :      str       						=						is_training
         __lowerCamelCase     :      Optional[int]       						=						use_input_mask
         __lowerCamelCase     :      str       						=						use_token_type_ids
         __lowerCamelCase     :      Dict       						=						use_labels
         __lowerCamelCase     :      Any       						=						vocab_size
         __lowerCamelCase     :      List[str]       						=						hidden_size
         __lowerCamelCase     :      List[Any]       						=						num_hidden_layers
         __lowerCamelCase     :      Any       						=						num_attention_heads
         __lowerCamelCase     :      int       						=						intermediate_size
         __lowerCamelCase     :      Optional[int]       						=						hidden_act
         __lowerCamelCase     :      Dict       						=						hidden_dropout_prob
         __lowerCamelCase     :      List[Any]       						=						attention_probs_dropout_prob
         __lowerCamelCase     :      Union[str, Any]       						=						max_position_embeddings
         __lowerCamelCase     :      Dict       						=						type_vocab_size
         __lowerCamelCase     :      List[Any]       						=						type_sequence_label_size
         __lowerCamelCase     :      Any       						=						initializer_range
         __lowerCamelCase     :      Any       						=						num_labels
         __lowerCamelCase     :      List[Any]       						=						num_choices
         __lowerCamelCase     :      Any       						=						relative_attention
         __lowerCamelCase     :      Dict       						=						position_biased_input
         __lowerCamelCase     :      Dict       						=						pos_att_type
         __lowerCamelCase     :      Optional[Any]       						=						scope

   def   _snake_case    (  self  : List[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size							)

         __lowerCamelCase     :      List[Any]       						=						None
         if self.use_input_mask:
               __lowerCamelCase     :      Union[str, Any]       						=						ids_tensor([self.batch_size, self.seq_length]       ,  vocab_size=2							)

         __lowerCamelCase     :      List[str]       						=						None
         if self.use_token_type_ids:
               __lowerCamelCase     :      int       						=						ids_tensor([self.batch_size, self.seq_length]       ,  self.type_vocab_size							)

         __lowerCamelCase     :      Union[str, Any]       						=						None
         __lowerCamelCase     :      Optional[Any]       						=						None
         __lowerCamelCase     :      Optional[int]       						=						None
         if self.use_labels:
               __lowerCamelCase     :      List[Any]       						=						ids_tensor([self.batch_size]       ,  self.type_sequence_label_size							)
               __lowerCamelCase     :      List[str]       						=						ids_tensor([self.batch_size, self.seq_length]       ,  self.num_labels							)
               __lowerCamelCase     :      str       						=						ids_tensor([self.batch_size]       ,  self.num_choices							)

         __lowerCamelCase     :      Tuple       						=						self.get_config()

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

   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         return DebertaVaConfig(
             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   _snake_case    (  self  : Tuple       ,  _lowerCamelCase  : List[str]							):






         '''simple docstring'''



         self.parent.assertListEqual(list(result.loss.size()							)       ,  []							)

   def   _snake_case    (  self  : Optional[Any]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : Tuple       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : Dict							):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						DebertaVaModel(config=_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      Optional[Any]       						=						model(_lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase							)[0]
         __lowerCamelCase     :      Union[str, Any]       						=						model(_lowerCamelCase       ,  token_type_ids=_lowerCamelCase							)[0]
         __lowerCamelCase     :      Dict       						=						model(_lowerCamelCase							)[0]

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

   def   _snake_case    (  self  : Optional[int]       ,  _lowerCamelCase  : Tuple       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Optional[int]       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : Tuple							):






         '''simple docstring'''



         __lowerCamelCase     :      Dict       						=						DebertaVaForMaskedLM(config=_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      Any       						=						model(_lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase       ,  labels=_lowerCamelCase							)

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

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






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						self.num_labels
         __lowerCamelCase     :      str       						=						DebertaVaForSequenceClassification(_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      List[str]       						=						model(_lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase       ,  labels=_lowerCamelCase							)
         self.parent.assertListEqual(list(result.logits.size()							)       ,  [self.batch_size, self.num_labels]							)
         self.check_loss_output(_lowerCamelCase							)

   def   _snake_case    (  self  : int       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : Union[str, Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						self.num_labels
         __lowerCamelCase     :      Tuple       						=						DebertaVaForTokenClassification(config=_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      List[Any]       						=						model(_lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase       ,  labels=_lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.num_labels)							)

   def   _snake_case    (  self  : List[Any]       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : Any       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : List[str]       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						DebertaVaForQuestionAnswering(config=_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      Dict       						=						model(
             _lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase       ,  start_positions=_lowerCamelCase       ,  end_positions=_lowerCamelCase       ,  )
         self.parent.assertEqual(result.start_logits.shape       ,  (self.batch_size, self.seq_length)							)
         self.parent.assertEqual(result.end_logits.shape       ,  (self.batch_size, self.seq_length)							)

   def   _snake_case    (  self  : Any       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Dict       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : Optional[Any]       ,  _lowerCamelCase  : Any       ,  _lowerCamelCase  : Any       ,  _lowerCamelCase  : int							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						DebertaVaForMultipleChoice(config=_lowerCamelCase							)
         model.to(_lowerCamelCase							)
         model.eval()
         __lowerCamelCase     :      Any       						=						input_ids.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
         __lowerCamelCase     :      str       						=						token_type_ids.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
         __lowerCamelCase     :      Optional[int]       						=						input_mask.unsqueeze(1							).expand(-1       ,  self.num_choices       ,  -1							).contiguous()
         __lowerCamelCase     :      Any       						=						model(
             _lowerCamelCase       ,  attention_mask=_lowerCamelCase       ,  token_type_ids=_lowerCamelCase       ,  labels=_lowerCamelCase       ,  )
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_choices)							)


   def   _snake_case    (  self  : int							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						self.prepare_config_and_inputs()
         (
             __lowerCamelCase 
         )     :      int       						=						config_and_inputs
         __lowerCamelCase     :      Tuple       						=						{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
         return config, inputs_dict



@require_torch
class 							_UpperCamelCase (						A,A,unittest.TestCase						):

   '''simple docstring'''







   a_				:							Tuple    =      (
       (
           DebertaVaModel,
           DebertaVaForMaskedLM,
           DebertaVaForSequenceClassification,
           DebertaVaForTokenClassification,
           DebertaVaForQuestionAnswering,
           DebertaVaForMultipleChoice,
       )
       if is_torch_available()
       else ()
   )
   a_				:							Tuple    =      (
       {
           "feature-extraction": DebertaVaModel,
           "fill-mask": DebertaVaForMaskedLM,
           "question-answering": DebertaVaForQuestionAnswering,
           "text-classification": DebertaVaForSequenceClassification,
           "token-classification": DebertaVaForTokenClassification,
           "zero-shot": DebertaVaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )

   a_				:							Tuple    =      True
   a_				:							Optional[Any]    =      False
   a_				:							Tuple    =      False
   a_				:							Any    =      False
   a_				:							List[Any]    =      False

   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						DebertaVaModelTester(self							)
         __lowerCamelCase     :      Optional[Any]       						=						ConfigTester(self       ,  config_class=_lowerCamelCase       ,  hidden_size=3_7							)

   def   _snake_case    (  self  : Any							):






         '''simple docstring'''



         self.config_tester.run_common_tests()

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_model(*_lowerCamelCase							)

   def   _snake_case    (  self  : int							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[int]       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_for_sequence_classification(*_lowerCamelCase							)

   def   _snake_case    (  self  : Union[str, Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_for_masked_lm(*_lowerCamelCase							)

   def   _snake_case    (  self  : str							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_for_question_answering(*_lowerCamelCase							)

   def   _snake_case    (  self  : int							):






         '''simple docstring'''



         __lowerCamelCase     :      int       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_for_token_classification(*_lowerCamelCase							)

   def   _snake_case    (  self  : Any							):






         '''simple docstring'''



         __lowerCamelCase     :      str       						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_deberta_for_multiple_choice(*_lowerCamelCase							)


   @slow
   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __lowerCamelCase     :      Any       						=						DebertaVaModel.from_pretrained(_lowerCamelCase							)
               self.assertIsNotNone(_lowerCamelCase							)



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

   '''simple docstring'''







   @unittest.skip(reason="""Model not available yet"""							)
   def   _snake_case    (  self  : Dict							):






         '''simple docstring'''



         pass


   @slow
   def   _snake_case    (  self  : Union[str, Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge"""							)

         __lowerCamelCase     :      Union[str, Any]       						=						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]]							)
         __lowerCamelCase     :      str       						=						torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
         with torch.no_grad():
               __lowerCamelCase     :      Optional[Any]       						=						model(_lowerCamelCase       ,  attention_mask=_lowerCamelCase							)[0]
         # compare the actual values for a slice.
         __lowerCamelCase     :      Dict       						=						torch.tensor(
             [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]]							)
         self.assertTrue(torch.allclose(output[:, 1:4, 1:4]       ,  _lowerCamelCase       ,  atol=1E-4							)       ,  F"""{output[:, 1:4, 1:4]}"""							)







import json
from typing import Iterator, List, Union

from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
from tokenizers.implementations.base_tokenizer import BaseTokenizer
from tokenizers.models import Unigram
from tokenizers.processors import TemplateProcessing



class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   def __init__(  self  : str       ,  _lowerCamelCase  : str = "▁"       ,  _lowerCamelCase  : bool = True       ,  _lowerCamelCase  : Union[str, AddedToken] = "<unk>"       ,  _lowerCamelCase  : Union[str, AddedToken] = "</s>"       ,  _lowerCamelCase  : Union[str, AddedToken] = "<pad>"       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						{
             """pad""": {"""id""": 0, """token""": pad_token},
             """eos""": {"""id""": 1, """token""": eos_token},
             """unk""": {"""id""": 2, """token""": unk_token},
         }

         __lowerCamelCase     :      Optional[Any]       						=						[None] * len(self.special_tokens							)
         for token_dict in self.special_tokens.values():
               __lowerCamelCase     :      Tuple       						=						token_dict["""token"""]

         __lowerCamelCase     :      Optional[int]       						=						Tokenizer(Unigram()							)

         __lowerCamelCase     :      str       						=						normalizers.Sequence(
             [
                 normalizers.Nmt(),
                 normalizers.NFKC(),
                 normalizers.Replace(Regex(""" {2,}"""							)       ,  """ """							),
                 normalizers.Lowercase(),
             ]							)
         __lowerCamelCase     :      int       						=						pre_tokenizers.Sequence(
             [
                 pre_tokenizers.Metaspace(replacement=_lowerCamelCase       ,  add_prefix_space=_lowerCamelCase							),
                 pre_tokenizers.Digits(individual_digits=_lowerCamelCase							),
                 pre_tokenizers.Punctuation(),
             ]							)
         __lowerCamelCase     :      Tuple       						=						decoders.Metaspace(replacement=_lowerCamelCase       ,  add_prefix_space=_lowerCamelCase							)

         __lowerCamelCase     :      Tuple       						=						TemplateProcessing(
             single=F"""$A {self.special_tokens["eos"]["token"]}"""       ,  special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])]       ,  )

         __lowerCamelCase     :      Tuple       						=						{
             """model""": """SentencePieceUnigram""",
             """replacement""": replacement,
             """add_prefix_space""": add_prefix_space,
         }

         super().__init__(_lowerCamelCase       ,  _lowerCamelCase							)

   def   _snake_case    (  self  : Dict       ,  _lowerCamelCase  : Union[str, List[str]]       ,  _lowerCamelCase  : int = 8_0_0_0       ,  _lowerCamelCase  : bool = True       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						trainers.UnigramTrainer(
             vocab_size=_lowerCamelCase       ,  special_tokens=self.special_tokens_list       ,  show_progress=_lowerCamelCase       ,  )

         if isinstance(_lowerCamelCase       ,  _lowerCamelCase							):
               __lowerCamelCase     :      Optional[int]       						=						[files]
         self._tokenizer.train(_lowerCamelCase       ,  trainer=_lowerCamelCase							)

         self.add_unk_id()

   def   _snake_case    (  self  : List[Any]       ,  _lowerCamelCase  : Union[Iterator[str], Iterator[Iterator[str]]]       ,  _lowerCamelCase  : int = 8_0_0_0       ,  _lowerCamelCase  : bool = True       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						trainers.UnigramTrainer(
             vocab_size=_lowerCamelCase       ,  special_tokens=self.special_tokens_list       ,  show_progress=_lowerCamelCase       ,  )

         self._tokenizer.train_from_iterator(_lowerCamelCase       ,  trainer=_lowerCamelCase							)

         self.add_unk_id()


   def   _snake_case    (  self  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      List[str]       						=						json.loads(self._tokenizer.to_str()							)

         __lowerCamelCase     :      Optional[int]       						=						self.special_tokens["""unk"""]["""id"""]

         __lowerCamelCase     :      List[str]       						=						Tokenizer.from_str(json.dumps(_lowerCamelCase							)							)



