

"""simple docstring"""

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       _snake_case  :







						def __init__(self  ,				UpperCAmelCase_  ,				UpperCAmelCase_=1_3  ,				UpperCAmelCase_=7  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=9_9  ,				UpperCAmelCase_=3_2  ,				UpperCAmelCase_=2  ,				UpperCAmelCase_=4  ,				UpperCAmelCase_=3_7  ,				UpperCAmelCase_="gelu"  ,				UpperCAmelCase_=0.1  ,				UpperCAmelCase_=0.1  ,				UpperCAmelCase_=5_1_2  ,				UpperCAmelCase_=1_6  ,				UpperCAmelCase_=2  ,				UpperCAmelCase_=0.0_2  ,				UpperCAmelCase_=3  ,				UpperCAmelCase_=4  ,				UpperCAmelCase_=None  ,				)      ->    int:
											__lowercase        =      parent
											__lowercase        =      1_3
											__lowercase        =      7
											__lowercase        =      True
											__lowercase        =      True
											__lowercase        =      True
											__lowercase        =      True
											__lowercase        =      9_9
											__lowercase        =      3_2
											__lowercase        =      2
											__lowercase        =      4
											__lowercase        =      3_7
											__lowercase        =      '''gelu'''
											__lowercase        =      0.1
											__lowercase        =      0.1
											__lowercase        =      5_1_2
											__lowercase        =      1_6
											__lowercase        =      False
											__lowercase        =      -1
											__lowercase        =      True
											__lowercase        =      2
											__lowercase        =      0.0_2
											__lowercase        =      3
											__lowercase        =      4
											__lowercase        =      None







						def 							_UpperCamelCase     (self				)      ->    List[str]:
											__lowercase        =      ids_tensor([self.batch_size, self.seq_length]  ,				self.vocab_size				)

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

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

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

											__lowercase        =      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 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Any:
											__lowercase        =      TFDebertaModel(config=_lowercase				)
											__lowercase        =      {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

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

											__lowercase        =      model(_lowercase				)

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







						def 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Tuple:
											__lowercase        =      TFDebertaForMaskedLM(config=_lowercase				)
											__lowercase        =      {
											    '''input_ids''': input_ids,
											    '''attention_mask''': input_mask,
											    '''token_type_ids''': token_type_ids,
											}
											__lowercase        =      model(_lowercase				)
											self.parent.assertEqual(result.logits.shape  ,				(self.batch_size, self.seq_length, self.vocab_size)				)







						def 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    List[Any]:
											__lowercase        =      self.num_labels
											__lowercase        =      TFDebertaForSequenceClassification(config=_lowercase				)
											__lowercase        =      {
											    '''input_ids''': input_ids,
											    '''attention_mask''': input_mask,
											    '''token_type_ids''': token_type_ids,
											}

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







						def 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Tuple:
											__lowercase        =      self.num_labels
											__lowercase        =      TFDebertaForTokenClassification(config=_lowercase				)
											__lowercase        =      {
											    '''input_ids''': input_ids,
											    '''attention_mask''': input_mask,
											    '''token_type_ids''': token_type_ids,
											}
											__lowercase        =      model(_lowercase				)
											self.parent.assertEqual(result.logits.shape  ,				(self.batch_size, self.seq_length, self.num_labels)				)







						def 							_UpperCamelCase     (self  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_  ,				UpperCAmelCase_				)      ->    Tuple:
											__lowercase        =      TFDebertaForQuestionAnswering(config=_lowercase				)
											__lowercase        =      {
											    '''input_ids''': input_ids,
											    '''attention_mask''': input_mask,
											    '''token_type_ids''': token_type_ids,
											}

											__lowercase        =      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 							_UpperCamelCase     (self				)      ->    List[str]:
											__lowercase        =      self.prepare_config_and_inputs()
											(
											    (
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,			(
											    __lowercase				
											)    ,							
											)        =      config_and_inputs
											__lowercase        =      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
											return config, inputs_dict



@require_tf
class       _snake_case  (    lowerCAmelCase__    ,      lowerCAmelCase__    ,      unittest.TestCase							):
						__snake_case			      =  (
						    (
						        TFDebertaModel,
						        TFDebertaForMaskedLM,
						        TFDebertaForQuestionAnswering,
						        TFDebertaForSequenceClassification,
						        TFDebertaForTokenClassification,
						    )
						    if is_tf_available()
						    else ()
						)
						__snake_case			      =  (
						    {
						        'feature-extraction': TFDebertaModel,
						        'fill-mask': TFDebertaForMaskedLM,
						        'question-answering': TFDebertaForQuestionAnswering,
						        'text-classification': TFDebertaForSequenceClassification,
						        'token-classification': TFDebertaForTokenClassification,
						        'zero-shot': TFDebertaForSequenceClassification,
						    }
						    if is_tf_available()
						    else {}
						)

						__snake_case			      =  False
						__snake_case			      =  False







						def 							_UpperCamelCase     (self				)      ->    int:
											__lowercase        =      TFDebertaModelTester(self				)
											__lowercase        =      ConfigTester(self  ,				config_class=_lowercase  ,				hidden_size=3_7				)







						def 							_UpperCamelCase     (self				)      ->    Union[str, Any]:
											self.config_tester.run_common_tests()







						def 							_UpperCamelCase     (self				)      ->    List[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowercase				)







						def 							_UpperCamelCase     (self				)      ->    int:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*_lowercase				)







						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(*_lowercase				)







						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(*_lowercase				)







						def 							_UpperCamelCase     (self				)      ->    Optional[Any]:
											__lowercase        =      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(*_lowercase				)







						@slow
						def 							_UpperCamelCase     (self				)      ->    str:
											__lowercase        =      TFDebertaModel.from_pretrained('''kamalkraj/deberta-base'''				)
											self.assertIsNotNone(_lowercase				)



@require_tf
class       _snake_case  (    unittest.TestCase							):







						@unittest.skip(reason='''Model not available yet'''				)
						def 							_UpperCamelCase     (self				)      ->    List[str]:
											pass







						@slow
						def 							_UpperCamelCase     (self				)      ->    Any:
											__lowercase        =      TFDebertaModel.from_pretrained('''kamalkraj/deberta-base'''				)
											__lowercase        =      tf.constant([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]				)
											__lowercase        =      tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]				)
											__lowercase        =      model(_lowercase  ,				attention_mask=_lowercase				)[0]

											__lowercase        =      tf.constant(
											    [
											        [
											            [-0.5_9_8_5_5_8_9_6, -0.8_0_5_5_2_5_6_6, -0.8_4_6_2_1_3_5],
											            [1.4_4_8_4_0_2_5, -0.9_3_4_8_3_7_9_4, -0.8_0_5_9_3_0_8_5],
											            [0.3_1_2_2_7_4_1, 0.0_0_3_1_6_0_5_9, -1.4_1_3_1_3_7_7],
											        ]
											    ]				)
											tf.debugging.assert_near(output[:, 1:4, 1:4]  ,				_lowercase  ,				atol=1e-4				)








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
	import PIL


__A						:		Dict          =						logging.get_logger(__name__)

class 		lowercase_       (	lowerCAmelCase__				):
					__UpperCamelCase     	= ["pixel_values"]




					def __init__(   self:		str,     _lowercase:		bool = True,     _lowercase:		Dict[str, int] = None,     _lowercase:		PILImageResampling = PIL.Image.NEAREST,     _lowercase:		bool = False,     _lowercase:		Dict[str, int] = None,     _lowercase:		Union[int, float] = 1 / 255,     _lowercase:		bool = False,     _lowercase:		bool = True,     _lowercase:		bool = True,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		bool = True,     **_lowercase:		Union[str, Any],     ):


									'''simple docstring'''


									super().__init__(**_lowercase)
									__lowerCAmelCase					=  size if size is not None else {"""height""": 346, """width""": 346}
									__lowerCAmelCase					=  get_size_dict(_lowercase)
									__lowerCAmelCase					=  crop_size if crop_size is not None else {"""height""": 289, """width""": 289}
									__lowerCAmelCase					=  get_size_dict(_lowercase,     param_name="""crop_size""")

									__lowerCAmelCase					=  do_resize
									__lowerCAmelCase					=  size
									__lowerCAmelCase					=  resample
									__lowerCAmelCase					=  do_center_crop
									__lowerCAmelCase					=  crop_size
									__lowerCAmelCase					=  do_rescale
									__lowerCAmelCase					=  rescale_factor
									__lowerCAmelCase					=  rescale_offset
									__lowerCAmelCase					=  do_normalize
									__lowerCAmelCase					=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									__lowerCAmelCase					=  image_std if image_std is not None else IMAGENET_STANDARD_STD
									__lowerCAmelCase					=  include_top




					def     _lowercase						(   self:		Optional[Any],     _lowercase:		np.ndarray,     _lowercase:		Dict[str, int],     _lowercase:		PILImageResampling = PIL.Image.NEAREST,     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Dict,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  get_size_dict(_lowercase)
									if "height" not in size or "width" not in size:
													raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
									return resize(
									    _lowercase,     size=(size["""height"""], size["""width"""]),     resample=_lowercase,     data_format=_lowercase,     **_lowercase)




					def     _lowercase						(   self:		List[str],     _lowercase:		np.ndarray,     _lowercase:		Dict[str, int],     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Tuple,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  get_size_dict(_lowercase)
									if "height" not in size or "width" not in size:
													raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''')
									return center_crop(_lowercase,     size=(size["""height"""], size["""width"""]),     data_format=_lowercase,     **_lowercase)




					def     _lowercase						(   self:		Union[str, Any],     _lowercase:		np.ndarray,     _lowercase:		Union[int, float],     _lowercase:		bool = True,     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Dict,     ):


									'''simple docstring'''


									if offset:
													__lowerCAmelCase					=  (image - 127.5) * scale
													if data_format is not None:
																	__lowerCAmelCase					=  to_channel_dimension_format(_lowercase,     _lowercase)
													__lowerCAmelCase					=  rescaled_image.astype(np.floataa)
									else:
													__lowerCAmelCase					=  rescale(_lowercase,     scale=_lowercase,     data_format=_lowercase,     **_lowercase)
									return rescaled_image




					def     _lowercase						(   self:		Dict,     _lowercase:		np.ndarray,     _lowercase:		Union[float, List[float]],     _lowercase:		Union[float, List[float]],     _lowercase:		Optional[Union[str, ChannelDimension]] = None,     **_lowercase:		Any,     ):


									'''simple docstring'''


									return normalize(_lowercase,     mean=_lowercase,     std=_lowercase,     data_format=_lowercase,     **_lowercase)







					def     _lowercase						(   self:		Dict,     _lowercase:		ImageInput,     _lowercase:		bool = None,     _lowercase:		Dict[str, int] = None,     _lowercase:		str=None,     _lowercase:		bool = None,     _lowercase:		Dict[str, int] = None,     _lowercase:		bool = None,     _lowercase:		float = None,     _lowercase:		bool = None,     _lowercase:		bool = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		Optional[Union[float, List[float]]] = None,     _lowercase:		bool = None,     _lowercase:		Optional[Union[str, TensorType]] = None,     _lowercase:		ChannelDimension = ChannelDimension.FIRST,     **_lowercase:		Tuple,     ):


									'''simple docstring'''


									__lowerCAmelCase					=  do_resize if do_resize is not None else self.do_resize
									__lowerCAmelCase					=  resample if resample is not None else self.resample
									__lowerCAmelCase					=  do_center_crop if do_center_crop is not None else self.do_center_crop
									__lowerCAmelCase					=  do_rescale if do_rescale is not None else self.do_rescale
									__lowerCAmelCase					=  rescale_factor if rescale_factor is not None else self.rescale_factor
									__lowerCAmelCase					=  rescale_offset if rescale_offset is not None else self.rescale_offset
									__lowerCAmelCase					=  do_normalize if do_normalize is not None else self.do_normalize
									__lowerCAmelCase					=  image_mean if image_mean is not None else self.image_mean
									__lowerCAmelCase					=  image_std if image_std is not None else self.image_std
									__lowerCAmelCase					=  include_top if include_top is not None else self.include_top

									__lowerCAmelCase					=  size if size is not None else self.size
									__lowerCAmelCase					=  get_size_dict(_lowercase)
									__lowerCAmelCase					=  crop_size if crop_size is not None else self.crop_size
									__lowerCAmelCase					=  get_size_dict(_lowercase,     param_name="""crop_size""")

									__lowerCAmelCase					=  make_list_of_images(_lowercase)

									if not valid_images(_lowercase):
													raise ValueError(
													    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
													    """torch.Tensor, tf.Tensor or jax.ndarray.""")

									if do_resize and size is None or resample is None:
													raise ValueError("""Size and resample must be specified if do_resize is True.""")

									if do_center_crop and crop_size is None:
													raise ValueError("""Crop size must be specified if do_center_crop is True.""")

									if do_rescale and rescale_factor is None:
													raise ValueError("""Rescale factor must be specified if do_rescale is True.""")

									if do_normalize and (image_mean is None or image_std is None):
													raise ValueError("""Image mean and std must be specified if do_normalize is True.""")

									# All transformations expect numpy arrays.
									__lowerCAmelCase					=  [to_numpy_array(_lowercase) for image in images]

									if do_resize:
													__lowerCAmelCase					=  [self.resize(image=_lowercase,     size=_lowercase,     resample=_lowercase) for image in images]

									if do_center_crop:
													__lowerCAmelCase					=  [self.center_crop(image=_lowercase,     size=_lowercase) for image in images]

									if do_rescale:
													__lowerCAmelCase					=  [self.rescale(image=_lowercase,     scale=_lowercase,     offset=_lowercase) for image in images]

									if do_normalize:
													__lowerCAmelCase					=  [self.normalize(image=_lowercase,     mean=_lowercase,     std=_lowercase) for image in images]

									if include_top:
													__lowerCAmelCase					=  [self.normalize(image=_lowercase,     mean=[0, 0, 0],     std=_lowercase) for image in images]

									__lowerCAmelCase					=  [to_channel_dimension_format(_lowercase,     _lowercase) for image in images]

									__lowerCAmelCase					=  {"""pixel_values""": images}
									return BatchFeature(data=_lowercase,     tensor_type=_lowercase)





