




from __future__ import annotations

import unittest

from transformers import DebertaConfig, 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 (
	    TFDebertaForMaskedLM,
	    TFDebertaForQuestionAnswering,
	    TFDebertaForSequenceClassification,
	    TFDebertaForTokenClassification,
	    TFDebertaModel,
	)

class 		lowercase_       :




					def __init__(   self:		Tuple,     _lowercase:		Tuple,     _lowercase:		Union[str, Any]=13,     _lowercase:		str=7,     _lowercase:		Dict=True,     _lowercase:		List[str]=True,     _lowercase:		Tuple=True,     _lowercase:		Optional[Any]=True,     _lowercase:		Optional[int]=99,     _lowercase:		Dict=32,     _lowercase:		Any=2,     _lowercase:		Optional[int]=4,     _lowercase:		List[Any]=37,     _lowercase:		Optional[Any]="gelu",     _lowercase:		Dict=0.1,     _lowercase:		Tuple=0.1,     _lowercase:		Any=512,     _lowercase:		List[Any]=16,     _lowercase:		List[str]=2,     _lowercase:		Any=0.02,     _lowercase:		Any=3,     _lowercase:		List[str]=4,     _lowercase:		List[str]=None,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  parent
									__lowerCAmelCase					=  13
									__lowerCAmelCase					=  7
									__lowerCAmelCase					=  True
									__lowerCAmelCase					=  True
									__lowerCAmelCase					=  True
									__lowerCAmelCase					=  True
									__lowerCAmelCase					=  99
									__lowerCAmelCase					=  32
									__lowerCAmelCase					=  2
									__lowerCAmelCase					=  4
									__lowerCAmelCase					=  37
									__lowerCAmelCase					=  """gelu"""
									__lowerCAmelCase					=  0.1
									__lowerCAmelCase					=  0.1
									__lowerCAmelCase					=  512
									__lowerCAmelCase					=  16
									__lowerCAmelCase					=  False
									__lowerCAmelCase					=  -1
									__lowerCAmelCase					=  True
									__lowerCAmelCase					=  2
									__lowerCAmelCase					=  0.02
									__lowerCAmelCase					=  3
									__lowerCAmelCase					=  4
									__lowerCAmelCase					=  None




					def     _lowercase						(   self:		Any):


									'''simple docstring'''


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

									__lowerCAmelCase					=  None
									if self.use_input_mask:
													__lowerCAmelCase					=  random_attention_mask([self.batch_size, self.seq_length])

									__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					=  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,     relative_attention=self.relative_attention,     max_relative_positions=self.max_relative_positions,     position_biased_input=self.position_biased_input,     initializer_range=self.initializer_range,     return_dict=_lowercase,     )

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




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


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaModel(config=_lowercase)
									__lowerCAmelCase					=  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

									__lowerCAmelCase					=  [input_ids, input_mask]
									__lowerCAmelCase					=  model(_lowercase)

									__lowerCAmelCase					=  model(_lowercase)

									self.parent.assertEqual(result.last_hidden_state.shape,     (self.batch_size, self.seq_length, self.hidden_size))




					def     _lowercase						(   self:		List[str],     _lowercase:		Any,     _lowercase:		Dict,     _lowercase:		Union[str, Any],     _lowercase:		List[str],     _lowercase:		int,     _lowercase:		Optional[int],     _lowercase:		Optional[Any]):


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaForMaskedLM(config=_lowercase)
									__lowerCAmelCase					=  {
									    """input_ids""": input_ids,
									    """attention_mask""": input_mask,
									    """token_type_ids""": token_type_ids,
									}
									__lowerCAmelCase					=  model(_lowercase)
									self.parent.assertEqual(result.logits.shape,     (self.batch_size, self.seq_length, self.vocab_size))




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


									'''simple docstring'''


									__lowerCAmelCase					=  self.num_labels
									__lowerCAmelCase					=  TFDebertaForSequenceClassification(config=_lowercase)
									__lowerCAmelCase					=  {
									    """input_ids""": input_ids,
									    """attention_mask""": input_mask,
									    """token_type_ids""": token_type_ids,
									}

									__lowerCAmelCase					=  model(_lowercase)
									self.parent.assertEqual(result.logits.shape,     (self.batch_size, self.num_labels))




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


									'''simple docstring'''


									__lowerCAmelCase					=  self.num_labels
									__lowerCAmelCase					=  TFDebertaForTokenClassification(config=_lowercase)
									__lowerCAmelCase					=  {
									    """input_ids""": input_ids,
									    """attention_mask""": input_mask,
									    """token_type_ids""": token_type_ids,
									}
									__lowerCAmelCase					=  model(_lowercase)
									self.parent.assertEqual(result.logits.shape,     (self.batch_size, self.seq_length, self.num_labels))




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


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaForQuestionAnswering(config=_lowercase)
									__lowerCAmelCase					=  {
									    """input_ids""": input_ids,
									    """attention_mask""": input_mask,
									    """token_type_ids""": token_type_ids,
									}

									__lowerCAmelCase					=  model(_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     _lowercase						(   self:		Optional[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_tf
class 		lowercase_       (	lowerCAmelCase__						,							lowerCAmelCase__						,							unittest.TestCase				):
					__UpperCamelCase     	= (
					    (
					        TFDebertaModel,
					        TFDebertaForMaskedLM,
					        TFDebertaForQuestionAnswering,
					        TFDebertaForSequenceClassification,
					        TFDebertaForTokenClassification,
					    )
					    if is_tf_available()
					    else ()
					)
					__UpperCamelCase     	= (
					    {
					        "feature-extraction": TFDebertaModel,
					        "fill-mask": TFDebertaForMaskedLM,
					        "question-answering": TFDebertaForQuestionAnswering,
					        "text-classification": TFDebertaForSequenceClassification,
					        "token-classification": TFDebertaForTokenClassification,
					        "zero-shot": TFDebertaForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)

					__UpperCamelCase     	= False
					__UpperCamelCase     	= False




					def     _lowercase						(   self:		Dict):


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaModelTester(self)
									__lowerCAmelCase					=  ConfigTester(self,     config_class=_lowercase,     hidden_size=37)




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


									'''simple docstring'''


									self.config_tester.run_common_tests()




					def     _lowercase						(   self:		List[Any]):


									'''simple docstring'''


									__lowerCAmelCase					=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowercase)




					def     _lowercase						(   self:		List[Any]):


									'''simple docstring'''


									__lowerCAmelCase					=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_lowercase)




					def     _lowercase						(   self:		List[str]):


									'''simple docstring'''


									__lowerCAmelCase					=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_question_answering(*_lowercase)




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


									'''simple docstring'''


									__lowerCAmelCase					=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_sequence_classification(*_lowercase)




					def     _lowercase						(   self:		str):


									'''simple docstring'''


									__lowerCAmelCase					=  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_lowercase)







					@slow
					def     _lowercase						(   self:		Any):


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaModel.from_pretrained("""kamalkraj/deberta-base""")
									self.assertIsNotNone(_lowercase)





@require_tf
class 		lowercase_       (	unittest.TestCase				):




					@unittest.skip(reason="""Model not available yet""")
					def     _lowercase						(   self:		Optional[Any]):


									'''simple docstring'''


									pass







					@slow
					def     _lowercase						(   self:		List[str]):


									'''simple docstring'''


									__lowerCAmelCase					=  TFDebertaModel.from_pretrained("""kamalkraj/deberta-base""")
									__lowerCAmelCase					=  tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
									__lowerCAmelCase					=  tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
									__lowerCAmelCase					=  model(_lowercase,     attention_mask=_lowercase)[0]

									__lowerCAmelCase					=  tf.constant(
									    [
									        [
									            [-0.59_855_896, -0.80_552_566, -0.8_462_135],
									            [1.4_484_025, -0.93_483_794, -0.80_593_085],
									            [0.3_122_741, 0.00_316_059, -1.4_131_377],
									        ]
									    ])
									tf.debugging.assert_near(output[:, 1:4, 1:4],     _lowercase,     atol=1e-4)






"""simple docstring"""


import posixpath
from pathlib import Path
from unittest.mock import patch

import pytest
from fsspec.implementations.local import AbstractFileSystem, LocalFileSystem, stringify_path
from fsspec.registry import _registry as _fsspec_registry




class 					UpperCamelCase   (							lowerCAmelCase__  ):
       SCREAMING_SNAKE_CASE_						      = "mock"







       def __init__(					self,				*lowerCAmelCase__,				lowerCAmelCase__,				**lowerCAmelCase__) -> Dict:
            super().__init__()
            snake_case_   			=   LocalFileSystem(*lowerCAmelCase__,				**lowerCAmelCase__)
            snake_case_   			=   Path(lowerCAmelCase__).resolve().as_posix() + '/'







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> Any:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.mkdir(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> str:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.makedirs(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__) -> Union[str, Any]:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.rmdir(lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__=True,				*lowerCAmelCase__,				**lowerCAmelCase__) -> Optional[Any]:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            snake_case_   			=   self._fs.ls(lowerCAmelCase__,				detail=lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)
            if detail:
                 return [{**info, "name": info["name"][len(self.local_root_dir) :]} for info in out]
            else:
                 return [name[len(self.local_root_dir) :] for name in out]







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> Dict:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            snake_case_   			=   dict(self._fs.info(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__))
            snake_case_   			=   out['name'][len(self.local_root_dir) :]
            return out







       def 						a_		(					self,				lowerCAmelCase__,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> str:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.cp_file(lowerCAmelCase__,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> Union[str, Any]:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.rm_file(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> List[Any]:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.rm(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__) -> Optional[Any]:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs._open(lowerCAmelCase__,				*lowerCAmelCase__,				**lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__) -> Tuple:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.created(lowerCAmelCase__)







       def 						a_		(					self,				lowerCAmelCase__) -> int:
            snake_case_   			=   posixpath.join(self.local_root_dir,				self._strip_protocol(lowerCAmelCase__))
            return self._fs.modified(lowerCAmelCase__)







       @classmethod
       def 						a_		(					cls,				lowerCAmelCase__) -> Any:
            snake_case_   			=   stringify_path(lowerCAmelCase__)
            if path.startswith('mock://'):
                 snake_case_   			=   path[7:]
            return path




class 					UpperCamelCase   (							lowerCAmelCase__  ):
       SCREAMING_SNAKE_CASE_						      = "tmp"
       SCREAMING_SNAKE_CASE_						      = None







       def __init__(					self,				*lowerCAmelCase__,				**lowerCAmelCase__) -> str:
            assert self.tmp_dir is not None, "TmpDirFileSystem.tmp_dir is not set"
            super().__init__(*lowerCAmelCase__,				**lowerCAmelCase__,				local_root_dir=self.tmp_dir,				auto_mkdir=lowerCAmelCase__)







       @classmethod
       def 						a_		(					cls,				lowerCAmelCase__) -> List[str]:
            snake_case_   			=   stringify_path(lowerCAmelCase__)
            if path.startswith('tmp://'):
                 snake_case_   			=   path[6:]
            return path







@pytest.fixture
def    UpperCAmelCase       (						)							-> Tuple:
     snake_case_   			=   MockFileSystem
     snake_case_   			=   TmpDirFileSystem
     yield
     del _fsspec_registry["mock"]
     del _fsspec_registry["tmp"]







@pytest.fixture
def    UpperCAmelCase       (						UpperCAmelCase		,   UpperCAmelCase   )							-> Tuple:
     snake_case_   			=   tmp_path_factory.mktemp('mockfs'   )
     return MockFileSystem(local_root_dir=UpperCAmelCase		,   auto_mkdir=UpperCAmelCase   )







@pytest.fixture
def    UpperCAmelCase       (						UpperCAmelCase		,   UpperCAmelCase   )							-> int:
     snake_case_   			=   tmp_path_factory.mktemp('tmpfs'   )
     with patch.object(UpperCAmelCase		,   'tmp_dir'		,   UpperCAmelCase   ):
          yield TmpDirFileSystem()

