






from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
		from PIL import Image

		from transformers import ConvNextImageProcessor



class  __UpperCAmelCase						:







			def __init__(      self:    Union[str, Any] ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    Dict=13 ,      UpperCAmelCase_:    int=32 ,      UpperCAmelCase_:    List[Any]=3 ,      UpperCAmelCase_:    Any=4 ,      UpperCAmelCase_:    Optional[Any]=[10, 20, 30, 40] ,      UpperCAmelCase_:    int=[2, 2, 3, 2] ,      UpperCAmelCase_:    Dict=True ,      UpperCAmelCase_:    Dict=True ,      UpperCAmelCase_:    Any=37 ,      UpperCAmelCase_:    Tuple="gelu" ,      UpperCAmelCase_:    Union[str, Any]=10 ,      UpperCAmelCase_:    str=0.02 ,      UpperCAmelCase_:    Union[str, Any]=3 ,      UpperCAmelCase_:    int=None ,      ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    parent
									_SCREAMING_SNAKE_CASE       =    batch_size
									_SCREAMING_SNAKE_CASE       =    image_size
									_SCREAMING_SNAKE_CASE       =    num_channels
									_SCREAMING_SNAKE_CASE       =    num_stages
									_SCREAMING_SNAKE_CASE       =    hidden_sizes
									_SCREAMING_SNAKE_CASE       =    depths
									_SCREAMING_SNAKE_CASE       =    is_training
									_SCREAMING_SNAKE_CASE       =    use_labels
									_SCREAMING_SNAKE_CASE       =    intermediate_size
									_SCREAMING_SNAKE_CASE       =    hidden_act
									_SCREAMING_SNAKE_CASE       =    type_sequence_label_size
									_SCREAMING_SNAKE_CASE       =    initializer_range
									_SCREAMING_SNAKE_CASE       =    scope







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

									_SCREAMING_SNAKE_CASE       =    self.get_config()

									return config, pixel_values, labels







			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									return ConvNextConfig(
									    num_channels=self.num_channels ,      hidden_sizes=self.hidden_sizes ,      depths=self.depths ,      num_stages=self.num_stages ,      hidden_act=self.hidden_act ,      is_decoder=lowerCamelCase_ ,      initializer_range=self.initializer_range ,      )







			def 				UpperCamelCase (      self:    Optional[Any] ,      UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Optional[int]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    TFConvNextModel(config=lowerCamelCase_	)
									_SCREAMING_SNAKE_CASE       =    model(lowerCamelCase_ ,      training=lowerCamelCase_	)
									# expected last hidden states: B, C, H // 32, W // 32
									self.parent.assertEqual(
									    result.last_hidden_state.shape ,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,      )







			def 				UpperCamelCase (      self:    List[Any] ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    Optional[int] ,      UpperCAmelCase_:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.type_sequence_label_size
									_SCREAMING_SNAKE_CASE       =    TFConvNextForImageClassification(lowerCamelCase_	)
									_SCREAMING_SNAKE_CASE       =    model(lowerCamelCase_ ,      labels=lowerCamelCase_ ,      training=lowerCamelCase_	)
									self.parent.assertEqual(result.logits.shape ,      (self.batch_size, self.type_sequence_label_size)	)







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







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.prepare_config_and_inputs()
									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    config_and_inputs
									_SCREAMING_SNAKE_CASE       =    {"""pixel_values""": pixel_values}
									return config, inputs_dict



@require_tf
class  __UpperCAmelCase						(__SCREAMING_SNAKE_CASE			,__SCREAMING_SNAKE_CASE			,unittest.TestCase       ):
			__snake_case							: Optional[Any]							=				(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
			__snake_case							: int							=				(
			    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
			    if is_tf_available()
			    else {}
			)

			__snake_case							: Any							=				False
			__snake_case							: Optional[Any]							=				False
			__snake_case							: List[str]							=				False
			__snake_case							: Tuple							=				False
			__snake_case							: List[str]							=				False







			def 				UpperCamelCase (      self:    Tuple	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    TFConvNextModelTester(self	)
									_SCREAMING_SNAKE_CASE       =    ConfigTester(
									    self ,      config_class=lowerCamelCase_ ,      has_text_modality=lowerCamelCase_ ,      hidden_size=37 ,      )







			@unittest.skip(reason="""ConvNext does not use inputs_embeds"""	)
			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									pass







			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""	)	) == 0 ,      reason="""TF does not support backprop for grouped convolutions on CPU.""" ,      )
			@slow
			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									super().test_keras_fit()







			@unittest.skip(reason="""ConvNext does not support input and output embeddings"""	)
			def 				UpperCamelCase (      self:    List[str]	):







									'''simple docstring'''




									pass







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

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

															_SCREAMING_SNAKE_CASE       =    ["""pixel_values"""]
															self.assertListEqual(arg_names[:1] ,      lowerCamelCase_	)







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase_	)







			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""	)	) == 0 ,      reason="""TF does not support backprop for grouped convolutions on CPU.""" ,      )
			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									super().test_dataset_conversion()







			def 				UpperCamelCase (      self:    str	):







									'''simple docstring'''




									def check_hidden_states_output(UpperCAmelCase_:    Any ,      UpperCAmelCase_:    Dict ,      UpperCAmelCase_:    Dict	):
															_SCREAMING_SNAKE_CASE       =    model_class(lowerCamelCase_	)

															_SCREAMING_SNAKE_CASE       =    model(**self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_	)	)
															_SCREAMING_SNAKE_CASE       =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															_SCREAMING_SNAKE_CASE       =    self.model_tester.num_stages
															self.assertEqual(len(lowerCamelCase_	) ,      expected_num_stages + 1	)

															# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]	) ,      [self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,      )

									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    True
															check_hidden_states_output(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_	)

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															_SCREAMING_SNAKE_CASE       =    True

															check_hidden_states_output(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_	)







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs_for_common()

									def check_equivalence(UpperCAmelCase_:    Optional[Any] ,      UpperCAmelCase_:    List[str] ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    Dict={}	):
															_SCREAMING_SNAKE_CASE       =    model(lowerCamelCase_ ,      return_dict=lowerCamelCase_ ,      **lowerCamelCase_	)
															_SCREAMING_SNAKE_CASE       =    model(lowerCamelCase_ ,      return_dict=lowerCamelCase_ ,      **lowerCamelCase_	).to_tuple()

															def recursive_check(UpperCAmelCase_:    Union[str, Any] ,      UpperCAmelCase_:    int	):
																					if isinstance(lowerCamelCase_ ,      (List, Tuple)	):
																											for tuple_iterable_value, dict_iterable_value in zip(lowerCamelCase_ ,      lowerCamelCase_	):
																																	recursive_check(lowerCamelCase_ ,      lowerCamelCase_	)
																					elif tuple_object is None:
																											return
																					else:
																											self.assertTrue(
																											    all(tf.equal(lowerCamelCase_ ,      lowerCamelCase_	)	) ,      msg=(
																											        """Tuple and dict output are not equal. Difference:"""
																											        F' {tf.math.reduce_max(tf.abs(tuple_object - dict_object	)	)}'
																											    ) ,      )

																					recursive_check(lowerCamelCase_ ,      lowerCamelCase_	)

									for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE       =    model_class(lowerCamelCase_	)

															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_	)
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_	)
															check_equivalence(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_	)

															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_ ,      return_labels=lowerCamelCase_	)
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_ ,      return_labels=lowerCamelCase_	)
															check_equivalence(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_	)

															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_	)
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_	)
															check_equivalence(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_ ,      {"""output_hidden_states""": True}	)

															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_ ,      return_labels=lowerCamelCase_	)
															_SCREAMING_SNAKE_CASE       =    self._prepare_for_class(lowerCamelCase_ ,      lowerCamelCase_ ,      return_labels=lowerCamelCase_	)
															check_equivalence(lowerCamelCase_ ,      lowerCamelCase_ ,      lowerCamelCase_ ,      {"""output_hidden_states""": True}	)







			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_	)







			@slow
			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""	)
									self.assertIsNotNone(lowerCamelCase_	)

def 			__lowerCamelCase     (						)				->    Any:






						"""simple docstring"""





						_SCREAMING_SNAKE_CASE       =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
						return image




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







			@cached_property
			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""	) if is_vision_available() else None







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







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""	)

									_SCREAMING_SNAKE_CASE       =    self.default_image_processor
									_SCREAMING_SNAKE_CASE       =    prepare_img()
									_SCREAMING_SNAKE_CASE       =    image_processor(images=lowerCamelCase_ ,      return_tensors="""tf"""	)

									# forward pass
									_SCREAMING_SNAKE_CASE       =    model(**lowerCamelCase_	)

									# verify the logits
									_SCREAMING_SNAKE_CASE       =    tf.TensorShape((1, 1_000)	)
									self.assertEqual(outputs.logits.shape ,      lowerCamelCase_	)

									_SCREAMING_SNAKE_CASE       =    tf.constant([-0.02_60, -0.47_39, 0.19_11]	)

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





"""simple docstring"""







import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_deberta import DebertaTokenizer


if TYPE_CHECKING:
						from transformers.pipelines.conversational import Conversation


__a      			= logging.get_logger(__name__)

__a      			= {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

__a      			= {
    "vocab_file": {
        "microsoft/deberta-base": "https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json",
        "microsoft/deberta-large": "https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json",
        "microsoft/deberta-xlarge": "https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json",
        "microsoft/deberta-base-mnli": "https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json",
        "microsoft/deberta-large-mnli": "https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json",
        "microsoft/deberta-xlarge-mnli": (
            "https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json"
        ),
    },
    "merges_file": {
        "microsoft/deberta-base": "https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt",
        "microsoft/deberta-large": "https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt",
        "microsoft/deberta-xlarge": "https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt",
        "microsoft/deberta-base-mnli": "https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt",
        "microsoft/deberta-large-mnli": "https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt",
        "microsoft/deberta-xlarge-mnli": (
            "https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt"
        ),
    },
}

__a      			= {
    "microsoft/deberta-base": 5_12,
    "microsoft/deberta-large": 5_12,
    "microsoft/deberta-xlarge": 5_12,
    "microsoft/deberta-base-mnli": 5_12,
    "microsoft/deberta-large-mnli": 5_12,
    "microsoft/deberta-xlarge-mnli": 5_12,
}

__a      			= {
    "microsoft/deberta-base": {"do_lower_case": False},
    "microsoft/deberta-large": {"do_lower_case": False},
}
class 				lowerCamelCase							(      __SCREAMING_SNAKE_CASE			):


							"""simple docstring"""
							SCREAMING_SNAKE_CASE              =   VOCAB_FILES_NAMES
							SCREAMING_SNAKE_CASE              =   PRETRAINED_VOCAB_FILES_MAP
							SCREAMING_SNAKE_CASE              =   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							SCREAMING_SNAKE_CASE              =   ["""input_ids""", """attention_mask""", """token_type_ids"""]
							SCREAMING_SNAKE_CASE              =   DebertaTokenizer






							def __init__(    self			:  Dict		,			lowerCamelCase_			:  Dict=None		,			lowerCamelCase_			:  Union[str, Any]=None		,			lowerCamelCase_			:  Tuple=None		,			lowerCamelCase_			:  Dict="replace"		,			lowerCamelCase_			:  List[Any]="[CLS]"		,			lowerCamelCase_			:  Optional[Any]="[SEP]"		,			lowerCamelCase_			:  List[Any]="[SEP]"		,			lowerCamelCase_			:  str="[CLS]"		,			lowerCamelCase_			:  List[str]="[UNK]"		,			lowerCamelCase_			:  Any="[PAD]"		,			lowerCamelCase_			:  Tuple="[MASK]"		,			lowerCamelCase_			:  List[str]=False		,			**lowerCamelCase_			:  List[str]		,			):
													super().__init__(
													    lowerCamelCase_		,			lowerCamelCase_		,			tokenizer_file=lowerCamelCase_		,			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_		,			)
													UpperCAmelCase__												=     kwargs.pop('''add_bos_token'''		,			lowerCamelCase_					)

													UpperCAmelCase__												=     json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()					)
													if pre_tok_state.get('''add_prefix_space'''		,			lowerCamelCase_					) != add_prefix_space:
																			UpperCAmelCase__												=     getattr(lowerCamelCase_		,			pre_tok_state.pop('''type'''					)					)
																			UpperCAmelCase__												=     add_prefix_space
																			UpperCAmelCase__												=     pre_tok_class(**lowerCamelCase_					)

													UpperCAmelCase__												=     add_prefix_space






							@property
							def        lowerCAmelCase  (    self			:  int					):
													if self._mask_token is None:
																			if self.verbose:
																									logger.error('''Using mask_token, but it is not set yet.'''					)
																			return None
													return str(self._mask_token					)






							@mask_token.setter
							def        lowerCAmelCase  (    self			:  Union[str, Any]		,			lowerCamelCase_			:  Union[str, Any]					):
													UpperCAmelCase__												=     AddedToken(lowerCamelCase_		,			lstrip=lowerCamelCase_		,			rstrip=lowerCamelCase_					) if isinstance(lowerCamelCase_		,			lowerCamelCase_					) else value
													UpperCAmelCase__												=     value






							def        lowerCAmelCase  (    self			:  int		,			lowerCamelCase_			:  List[int]		,			lowerCamelCase_			:  Optional[List[int]] = None					):
													if token_ids_a is None:
																			return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													UpperCAmelCase__												=     [self.cls_token_id]
													UpperCAmelCase__												=     [self.sep_token_id]
													return cls + token_ids_a + sep + token_ids_a + sep






							def        lowerCAmelCase  (    self			:  Optional[Any]		,			lowerCamelCase_			:  List[int]		,			lowerCamelCase_			:  Optional[List[int]] = None					):
													UpperCAmelCase__												=     [self.sep_token_id]
													UpperCAmelCase__												=     [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					) * [0] + len(token_ids_a + sep					) * [1]






							def        lowerCAmelCase  (    self			:  Tuple		,			*lowerCamelCase_			:  Optional[int]		,			**lowerCamelCase_			:  Union[str, Any]					):
													UpperCAmelCase__												=     kwargs.get('''is_split_into_words'''		,			lowerCamelCase_					)
													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._batch_encode_plus(*lowerCamelCase_		,			**lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Tuple		,			*lowerCamelCase_			:  str		,			**lowerCamelCase_			:  Any					):
													UpperCAmelCase__												=     kwargs.get('''is_split_into_words'''		,			lowerCamelCase_					)

													assert self.add_prefix_space or not is_split_into_words, (
													    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
													    "to use it with pretokenized inputs."
													)

													return super()._encode_plus(*lowerCamelCase_		,			**lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Dict		,			lowerCamelCase_			:  str		,			lowerCamelCase_			:  Optional[str] = None					):
													UpperCAmelCase__												=     self._tokenizer.model.save(lowerCamelCase_		,			name=lowerCamelCase_					)
													return tuple(lowerCamelCase_					)






							def        lowerCAmelCase  (    self			:  Optional[Any]		,			lowerCamelCase_			:  "Conversation"					):
													UpperCAmelCase__												=     []
													for is_user, text in conversation.iter_texts():
																			input_ids.extend(self.encode(lowerCamelCase_		,			add_special_tokens=lowerCamelCase_					) + [self.eos_token_id]					)

													if len(lowerCamelCase_					) > self.model_max_length:
																			UpperCAmelCase__												=     input_ids[-self.model_max_length :]
													return input_ids