






import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
     from transformers.pipelines.conversational import Conversation

UpperCAmelCase__				   =		logging.get_logger(__name__)


UpperCAmelCase__				   =		{
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
    "tokenizer_config_file": "tokenizer_config.json",
}

UpperCAmelCase__				   =		{
    "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
    "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
    "tokenizer_config_file": {
        "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
    },
}

UpperCAmelCase__				   =		{"facebook/blenderbot-3B": 128}
@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def 						_a    (      )							->			Dict:
 a		  =      (
     list(range(ord('''!''' )	,							ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' )	,							ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' )	,							ord('''ÿ''' ) + 1 ) )
 )
 a		  =      bs[:]
 a		  =      0
 for b in range(2**8 ):
  if b not in bs:
   bs.append(UpperCamelCase__ )
   cs.append(2**8 + n )
   n += 1
 a		  =      [chr(UpperCamelCase__ ) for n in cs]
 return dict(zip(UpperCamelCase__	,							UpperCamelCase__ ) )
def 						_a    (      a :List[Any] )							->			int:
 a		  =      set()
 a		  =      word[0]
 for char in word[1:]:
  pairs.add((prev_char, char) )
  a		  =      char
 return pairs






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  VOCAB_FILES_NAMES
      __snake_case       =  PRETRAINED_VOCAB_FILES_MAP
      __snake_case       =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __snake_case       =  ['''input_ids''', '''attention_mask''']







      def __init__(      self      :						Optional[int] ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						Any ,					__UpperCAmelCase      :						Dict="replace" ,					__UpperCAmelCase      :						Optional[int]="<s>" ,					__UpperCAmelCase      :						Any="</s>" ,					__UpperCAmelCase      :						Tuple="</s>" ,					__UpperCAmelCase      :						Optional[Any]="<s>" ,					__UpperCAmelCase      :						str="<unk>" ,					__UpperCAmelCase      :						Dict="<pad>" ,					__UpperCAmelCase      :						List[Any]="<mask>" ,					__UpperCAmelCase      :						List[str]=False ,					**__UpperCAmelCase      :						Tuple ,					)    ->Optional[Any]:




       """simple docstring"""


       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else bos_token
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else eos_token
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else sep_token
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else cls_token
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else unk_token
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else pad_token

       # Mask token behave like a normal word, i.e. include the space before it
       a		  =      AddedToken(lowerCamelCase__ ,					lstrip=lowerCamelCase__ ,					rstrip=lowerCamelCase__  ) if isinstance(lowerCamelCase__ ,					lowerCamelCase__  ) else mask_token

       super().__init__(
           errors=lowerCamelCase__ ,					bos_token=lowerCamelCase__ ,					eos_token=lowerCamelCase__ ,					unk_token=lowerCamelCase__ ,					sep_token=lowerCamelCase__ ,					cls_token=lowerCamelCase__ ,					pad_token=lowerCamelCase__ ,					mask_token=lowerCamelCase__ ,					add_prefix_space=lowerCamelCase__ ,					**lowerCamelCase__ ,					)

       with open(lowerCamelCase__ ,					encoding='''utf-8'''  ) as vocab_handle:
        a		  =      json.load(lowerCamelCase__  )
       a		  =      {v: k for k, v in self.encoder.items()}
       a		  =      errors  # how to handle errors in decoding
       a		  =      bytes_to_unicode()
       a		  =      {v: k for k, v in self.byte_encoder.items()}
       with open(lowerCamelCase__ ,					encoding='''utf-8'''  ) as merges_handle:
        a		  =      merges_handle.read().split('''\n'''  )[1:-1]
       a		  =      [tuple(merge.split()  ) for merge in bpe_merges]
       a		  =      dict(zip(lowerCamelCase__ ,					range(len(lowerCamelCase__  )  )  )  )
       a		  =      {}
       a		  =      add_prefix_space

       # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
       a		  =      re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'''  )







      @property
      # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot
      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Any:




       """simple docstring"""


       return len(self.encoder  )







      def       __lowerCAmelCase					(      self      :						int  )    ->str:




       """simple docstring"""


       return dict(self.encoder ,					**self.added_tokens_encoder  )







      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Optional[Any]  )    ->Dict:




       """simple docstring"""


       if token in self.cache:
        return self.cache[token]
       a		  =      tuple(lowerCamelCase__  )
       a		  =      get_pairs(lowerCamelCase__  )

       if not pairs:
        return token

       while True:
        a		  =      min(lowerCamelCase__ ,					key=lambda __UpperCAmelCase  : self.bpe_ranks.get(lowerCamelCase__ ,					float('''inf'''  )  )  )
        if bigram not in self.bpe_ranks:
         break
        a  ,     a		  =      bigram
        a		  =      []
        a		  =      0
        while i < len(lowerCamelCase__  ):
         try:
          a		  =      word.index(lowerCamelCase__ ,					lowerCamelCase__  )
         except ValueError:
          new_word.extend(word[i:]  )
          break
         else:
          new_word.extend(word[i:j]  )
          a		  =      j

         if word[i] == first and i < len(lowerCamelCase__  ) - 1 and word[i + 1] == second:
          new_word.append(first + second  )
          i += 2
         else:
          new_word.append(word[i]  )
          i += 1
        a		  =      tuple(lowerCamelCase__  )
        a		  =      new_word
        if len(lowerCamelCase__  ) == 1:
         break
        else:
         a		  =      get_pairs(lowerCamelCase__  )
       a		  =      ''' '''.join(lowerCamelCase__  )
       a		  =      word
       return word







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




       """simple docstring"""


       a		  =      []
       for token in re.findall(self.pat ,					lowerCamelCase__  ):
        a		  =      ''''''.join(
            self.byte_encoder[b] for b in token.encode('''utf-8'''  )  )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
        bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase__  ).split(''' '''  )  )
       return bpe_tokens







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




       """simple docstring"""


       return self.encoder.get(lowerCamelCase__ ,					self.encoder.get(self.unk_token  )  )







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




       """simple docstring"""


       return self.decoder.get(lowerCamelCase__  )







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




       """simple docstring"""


       a		  =      ''''''.join(lowerCamelCase__  )
       a		  =      bytearray([self.byte_decoder[c] for c in text]  ).decode('''utf-8''' ,					errors=self.errors  )
       return text







      def       __lowerCAmelCase					(      self      :						List[Any] ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						Optional[Any] = None  )    ->Tuple[str]:




       """simple docstring"""


       if not os.path.isdir(lowerCamelCase__  ):
        logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""  )
        return
       a		  =      os.path.join(
           lowerCamelCase__ ,					(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']  )
       a		  =      os.path.join(
           lowerCamelCase__ ,					(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']  )

       with open(lowerCamelCase__ ,					'''w''' ,					encoding='''utf-8'''  ) as f:
        f.write(json.dumps(self.encoder ,					indent=2 ,					sort_keys=lowerCamelCase__ ,					ensure_ascii=lowerCamelCase__  ) + '''\n'''  )

       a		  =      0
       with open(lowerCamelCase__ ,					'''w''' ,					encoding='''utf-8'''  ) as writer:
        writer.write('''#version: 0.2\n'''  )
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,					key=lambda __UpperCAmelCase  : kv[1]  ):
         if index != token_index:
          logger.warning(
              F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
              ''' Please check that the tokenizer is not corrupted!'''  )
          a		  =      token_index
         writer.write(''' '''.join(lowerCamelCase__  ) + '''\n'''  )
         index += 1

       return vocab_file, merge_file







      def       __lowerCAmelCase					(      self      :						List[Any] ,					__UpperCAmelCase      :						Dict ,					__UpperCAmelCase      :						int = None ,					__UpperCAmelCase      :						Union[str, Any] = False  )    ->List[int]:




       """simple docstring"""


       if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=lowerCamelCase__ ,					token_ids_a=lowerCamelCase__ ,					already_has_special_tokens=lowerCamelCase__  )

       if token_ids_a is None:
        return [1] + ([0] * len(lowerCamelCase__  )) + [1]
       return [1] + ([0] * len(lowerCamelCase__  )) + [1, 1] + ([0] * len(lowerCamelCase__  )) + [1]







      def       __lowerCAmelCase					(      self      :						Dict ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						int = None  )    ->List[int]:




       """simple docstring"""


       a		  =      [self.sep_token_id]
       a		  =      [self.cls_token_id]

       if token_ids_a is None:
        return len(cls + token_ids_a + sep  ) * [0]
       return len(cls + token_ids_a + sep + sep + token_ids_a + sep  ) * [0]







      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						Optional[int] ,					__UpperCAmelCase      :						Tuple=False ,					**__UpperCAmelCase      :						Optional[Any]  )    ->Dict:




       """simple docstring"""


       a		  =      kwargs.pop('''add_prefix_space''' ,					self.add_prefix_space  )
       if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase__  ) > 0 and not text[0].isspace()):
        a		  =      ''' ''' + text
       return (text, kwargs)







      def       __lowerCAmelCase					(      self      :						List[Any] ,					__UpperCAmelCase      :						Optional[int] ,					__UpperCAmelCase      :						Dict = None  )    ->Any:




       """simple docstring"""


       return token_ids_a + [self.eos_token_id]







      def       __lowerCAmelCase					(      self      :						Union[str, Any] ,					__UpperCAmelCase      :						Optional[Any]  )    ->List[int]:




       """simple docstring"""


       a		  =      []
       for is_user, text in conversation.iter_texts():
        if is_user:
         # We need to space prefix as it's being done within blenderbot
         inputs.append(''' ''' + text  )
        else:
         # Generated responses should contain them already.
         inputs.append(lowerCamelCase__  )

       a		  =      '''  '''.join(lowerCamelCase__  )
       a		  =      self.encode(lowerCamelCase__  )
       if len(lowerCamelCase__  ) > self.model_max_length:
        a		  =      input_ids[-self.model_max_length :]
        logger.warning(F"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens."""  )
       return input_ids








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     __lowerCAmelCase (       __magic_name__ ):

			"""simple docstring"""







			def __init__(      self			,						lowerCamelCase__			,						lowerCamelCase__=13			,						lowerCamelCase__=7			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=True			,						lowerCamelCase__=99			,						lowerCamelCase__=32			,						lowerCamelCase__=5			,						lowerCamelCase__=4			,						lowerCamelCase__=37			,						lowerCamelCase__="gelu"			,						lowerCamelCase__=0.1			,						lowerCamelCase__=0.1			,						lowerCamelCase__=512			,						lowerCamelCase__=16			,						lowerCamelCase__=2			,						lowerCamelCase__=0.02			,						lowerCamelCase__=False			,						lowerCamelCase__=True			,						lowerCamelCase__="None"			,						lowerCamelCase__=3			,						lowerCamelCase__=4			,						lowerCamelCase__=None			,						)    ->      int:



							'''simple docstring'''
							__lowerCamelCase		       =    parent
							__lowerCamelCase		       =    batch_size
							__lowerCamelCase		       =    seq_length
							__lowerCamelCase		       =    is_training
							__lowerCamelCase		       =    use_input_mask
							__lowerCamelCase		       =    use_token_type_ids
							__lowerCamelCase		       =    use_labels
							__lowerCamelCase		       =    vocab_size
							__lowerCamelCase		       =    hidden_size
							__lowerCamelCase		       =    num_hidden_layers
							__lowerCamelCase		       =    num_attention_heads
							__lowerCamelCase		       =    intermediate_size
							__lowerCamelCase		       =    hidden_act
							__lowerCamelCase		       =    hidden_dropout_prob
							__lowerCamelCase		       =    attention_probs_dropout_prob
							__lowerCamelCase		       =    max_position_embeddings
							__lowerCamelCase		       =    type_vocab_size
							__lowerCamelCase		       =    type_sequence_label_size
							__lowerCamelCase		       =    initializer_range
							__lowerCamelCase		       =    num_labels
							__lowerCamelCase		       =    num_choices
							__lowerCamelCase		       =    relative_attention
							__lowerCamelCase		       =    position_biased_input
							__lowerCamelCase		       =    pos_att_type
							__lowerCamelCase		       =    scope


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size							)

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

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

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

							__lowerCamelCase		       =    self.get_config()

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


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



							'''simple docstring'''
							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       lowercase_    (      self							)    ->      List[str]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.get_config()
							__lowerCamelCase		       =    300
							return config


			def       lowercase_    (      self			,						lowerCamelCase__							)    ->      Optional[int]:



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


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Any:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModel(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)[0]
							__lowerCamelCase		       =    model(lowerCamelCase__			,						token_type_ids=lowerCamelCase__							)[0]
							__lowerCamelCase		       =    model(lowerCamelCase__							)[0]

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


			def       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaForMaskedLM(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    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       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.num_labels
							__lowerCamelCase		       =    DebertaForSequenceClassification(lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    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       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Optional[int]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.num_labels
							__lowerCamelCase		       =    DebertaForTokenClassification(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    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       lowercase_    (      self			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__			,						lowerCamelCase__							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaForQuestionAnswering(config=lowerCamelCase__							)
							model.to(lowerCamelCase__							)
							model.eval()
							__lowerCamelCase		       =    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       lowercase_    (      self							)    ->      Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase		       =    self.prepare_config_and_inputs()
							(
							    (
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						(
							    __lowerCamelCase
							)       ,						
							)		       =    config_and_inputs
							__lowerCamelCase		       =    {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
							return config, inputs_dict







@require_torch
class     __lowerCAmelCase (       __magic_name__			,				__magic_name__			,				unittest.TestCase ):

			"""simple docstring"""







			snake_case_   		=       (
			    (
			        DebertaModel,
			        DebertaForMaskedLM,
			        DebertaForSequenceClassification,
			        DebertaForTokenClassification,
			        DebertaForQuestionAnswering,
			    )
			    if is_torch_available()
			    else ()
			)
			snake_case_   		=       (
			    {
			        '''feature-extraction''': DebertaModel,
			        '''fill-mask''': DebertaForMaskedLM,
			        '''question-answering''': DebertaForQuestionAnswering,
			        '''text-classification''': DebertaForSequenceClassification,
			        '''token-classification''': DebertaForTokenClassification,
			        '''zero-shot''': DebertaForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)

			snake_case_   		=       True
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False
			snake_case_   		=       False


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



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModelTester(self							)
							__lowerCamelCase		       =    ConfigTester(self			,						config_class=lowerCamelCase__			,						hidden_size=37							)


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



							'''simple docstring'''
							self.config_tester.run_common_tests()


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_model(*lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCamelCase__							)


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



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_question_answering(*lowerCamelCase__							)


			def       lowercase_    (      self							)    ->      str:



							'''simple docstring'''
							__lowerCamelCase		       =    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_token_classification(*lowerCamelCase__							)






			@slow
			def       lowercase_    (      self							)    ->      Optional[int]:



							'''simple docstring'''
							for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase		       =    DebertaModel.from_pretrained(lowerCamelCase__							)
											self.assertIsNotNone(lowerCamelCase__							)







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

			"""simple docstring"""







			@unittest.skip(reason='Model not available yet'							)
			def       lowercase_    (      self							)    ->      Union[str, Any]:



							'''simple docstring'''
							pass






			@slow
			def       lowercase_    (      self							)    ->      Tuple:



							'''simple docstring'''
							__lowerCamelCase		       =    DebertaModel.from_pretrained('microsoft/deberta-base'							)

							__lowerCamelCase		       =    torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]							)
							__lowerCamelCase		       =    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
							with torch.no_grad():
											__lowerCamelCase		       =    model(lowerCamelCase__			,						attention_mask=lowerCamelCase__							)[0]
							# compare the actual values for a slice.
							__lowerCamelCase		       =    torch.tensor(
							    [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]]							)
							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]			,						lowerCamelCase__			,						atol=1e-4							)			,						f"""{output[:, 1:4, 1:4]}"""							)


