



"""simple docstring"""


from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
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 (
				    TFDeiTForImageClassification,
				    TFDeiTForImageClassificationWithTeacher,
				    TFDeiTForMaskedImageModeling,
				    TFDeiTModel,
				)
				from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import DeiTImageProcessor







class 				A_      :



						"""simple docstring"""






						def __init__( self			:Optional[Any]       ,  lowercase_			:str       ,  lowercase_			:Tuple=13       ,  lowercase_			:List[Any]=30       ,  lowercase_			:Optional[int]=2       ,  lowercase_			:Dict=3       ,  lowercase_			:Union[str, Any]=True       ,  lowercase_			:int=True       ,  lowercase_			:Optional[int]=32       ,  lowercase_			:Union[str, Any]=2       ,  lowercase_			:List[str]=4       ,  lowercase_			:List[Any]=37       ,  lowercase_			:Optional[int]="gelu"       ,  lowercase_			:List[str]=0.1       ,  lowercase_			:str=0.1       ,  lowercase_			:List[Any]=10       ,  lowercase_			:Tuple=0.02       ,  lowercase_			:Union[str, Any]=3       ,  lowercase_			:Any=None       ,  lowercase_			:Optional[Any]=2       ,  )    ->      Any:
												UpperCAmelCase					=			parent
												UpperCAmelCase					=			batch_size
												UpperCAmelCase					=			image_size
												UpperCAmelCase					=			patch_size
												UpperCAmelCase					=			num_channels
												UpperCAmelCase					=			is_training
												UpperCAmelCase					=			use_labels
												UpperCAmelCase					=			hidden_size
												UpperCAmelCase					=			num_hidden_layers
												UpperCAmelCase					=			num_attention_heads
												UpperCAmelCase					=			intermediate_size
												UpperCAmelCase					=			hidden_act
												UpperCAmelCase					=			hidden_dropout_prob
												UpperCAmelCase					=			attention_probs_dropout_prob
												UpperCAmelCase					=			type_sequence_label_size
												UpperCAmelCase					=			initializer_range
												UpperCAmelCase					=			scope
												UpperCAmelCase					=			encoder_stride

												# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
												UpperCAmelCase					=			(image_size // patch_size) ** 2
												UpperCAmelCase					=			num_patches + 2






						def      UpperCAmelCase__					( self			:List[str] )    ->      Optional[Any]:
												UpperCAmelCase					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

												UpperCAmelCase					=			self.get_config()

												return config, pixel_values, labels






						def      UpperCAmelCase__					( self			:List[str] )    ->      Union[str, Any]:
												return DeiTConfig(
												    image_size=self.image_size       ,  patch_size=self.patch_size       ,  num_channels=self.num_channels       ,  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       ,  is_decoder=lowercase_       ,  initializer_range=self.initializer_range       ,  encoder_stride=self.encoder_stride       ,  )






						def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:List[Any]       ,  lowercase_			:str       ,  lowercase_			:Optional[Any] )    ->      List[Any]:
												UpperCAmelCase					=			TFDeiTModel(config=lowercase_ )
												UpperCAmelCase					=			model(lowercase_ )
												self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size) )






						def      UpperCAmelCase__					( self			:int       ,  lowercase_			:int       ,  lowercase_			:Dict       ,  lowercase_			:Union[str, Any] )    ->      Tuple:
												UpperCAmelCase					=			TFDeiTForMaskedImageModeling(config=lowercase_ )
												UpperCAmelCase					=			model(lowercase_ )
												self.parent.assertEqual(
												    result.reconstruction.shape       ,  (self.batch_size, self.num_channels, self.image_size, self.image_size) )

												# test greyscale images
												UpperCAmelCase					=			1
												UpperCAmelCase					=			TFDeiTForMaskedImageModeling(lowercase_ )

												UpperCAmelCase					=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
												UpperCAmelCase					=			model(lowercase_ )
												self.parent.assertEqual(result.reconstruction.shape       ,  (self.batch_size, 1, self.image_size, self.image_size) )






						def      UpperCAmelCase__					( self			:List[Any]       ,  lowercase_			:int       ,  lowercase_			:int       ,  lowercase_			:str )    ->      Union[str, Any]:
												UpperCAmelCase					=			self.type_sequence_label_size
												UpperCAmelCase					=			TFDeiTForImageClassification(lowercase_ )
												UpperCAmelCase					=			model(lowercase_       ,  labels=lowercase_ )
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.type_sequence_label_size) )

												# test greyscale images
												UpperCAmelCase					=			1
												UpperCAmelCase					=			TFDeiTForImageClassification(lowercase_ )

												UpperCAmelCase					=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
												UpperCAmelCase					=			model(lowercase_       ,  labels=lowercase_ )
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.type_sequence_label_size) )






						def      UpperCAmelCase__					( self			:Tuple )    ->      Union[str, Any]:
												UpperCAmelCase					=			self.prepare_config_and_inputs()
												UpperCAmelCase				,   UpperCAmelCase				,   UpperCAmelCase					=			config_and_inputs
												UpperCAmelCase					=			{'pixel_values': pixel_values}
												return config, inputs_dict







@require_tf
class 				A_      (					SCREAMING_SNAKE_CASE_     ,       SCREAMING_SNAKE_CASE_     ,       unittest.TestCase    ):



						"""simple docstring"""
						__UpperCamelCase		    =							(
						    (
						        TFDeiTModel,
						        TFDeiTForImageClassification,
						        TFDeiTForImageClassificationWithTeacher,
						        TFDeiTForMaskedImageModeling,
						    )
						    if is_tf_available()
						    else ()
						)
						__UpperCamelCase		    =							(
						    {
						        """feature-extraction""": TFDeiTModel,
						        """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
						    }
						    if is_tf_available()
						    else {}
						)

						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Tuple:
												UpperCAmelCase					=			TFDeiTModelTester(self )
												UpperCAmelCase					=			ConfigTester(self       ,  config_class=lowercase_       ,  has_text_modality=lowercase_       ,  hidden_size=37 )






						def      UpperCAmelCase__					( self			:str )    ->      List[Any]:
												self.config_tester.run_common_tests()






						@unittest.skip(reason='DeiT does not use inputs_embeds' )
						def      UpperCAmelCase__					( self			:str )    ->      Any:
												pass






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Optional[Any]:
												UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		UpperCAmelCase					=			model_class(lowercase_ )
																		self.assertIsInstance(model.get_input_embeddings()       ,  (tf.keras.layers.Layer) )
																		UpperCAmelCase					=			model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(lowercase_       ,  tf.keras.layers.Dense ) )






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Any:
												UpperCAmelCase				,   UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs_for_common()

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

																		UpperCAmelCase					=			['pixel_values']
																		self.assertListEqual(arg_names[:1]       ,  lowercase_ )






						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      Union[str, Any]:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*lowercase_ )






						def      UpperCAmelCase__					( self			:Any )    ->      List[Any]:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_ )






						def      UpperCAmelCase__					( self			:str )    ->      Optional[Any]:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*lowercase_ )






						def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:Any       ,  lowercase_			:Union[str, Any]       ,  lowercase_			:Optional[Any]=False )    ->      str:
												UpperCAmelCase					=			super()._prepare_for_class(lowercase_       ,  lowercase_       ,  return_labels=lowercase_ )

												if return_labels:
																		if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters:
																								del inputs_dict["labels"]

												return inputs_dict






						@slow
						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      int:
												for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCAmelCase					=			TFDeiTModel.from_pretrained(lowercase_ )
																		self.assertIsNotNone(lowercase_ )


def 			_lowerCAmelCase				(       ):
						UpperCAmelCase					=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image







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



						"""simple docstring"""






						@cached_property
						def      UpperCAmelCase__					( self			:Any )    ->      str:
												return (
												    DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' )
												    if is_vision_available()
												    else None
												)






						@slow
						def      UpperCAmelCase__					( self			:Optional[Any] )    ->      int:
												UpperCAmelCase					=			TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' )

												UpperCAmelCase					=			self.default_image_processor
												UpperCAmelCase					=			prepare_img()
												UpperCAmelCase					=			image_processor(images=lowercase_       ,  return_tensors='tf' )

												# forward pass
												UpperCAmelCase					=			model(**lowercase_ )

												# verify the logits
												UpperCAmelCase					=			tf.TensorShape((1, 10_00) )
												self.assertEqual(outputs.logits.shape       ,  lowercase_ )

												UpperCAmelCase					=			tf.constant([-1.0266, 0.1912, -1.2861] )

												self.assertTrue(np.allclose(outputs.logits[0, :3]       ,  lowercase_       ,  atol=1E-4 ) )










"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


snake_case_    					=	{
    """configuration_rembert""": ["""REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RemBertConfig""", """RemBertOnnxConfig"""]
}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				snake_case_    					=	["""RemBertTokenizer"""]

try:
				if not is_tokenizers_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				snake_case_    					=	["""RemBertTokenizerFast"""]

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				snake_case_    					=	[
				    """REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """RemBertForCausalLM""",
				    """RemBertForMaskedLM""",
				    """RemBertForMultipleChoice""",
				    """RemBertForQuestionAnswering""",
				    """RemBertForSequenceClassification""",
				    """RemBertForTokenClassification""",
				    """RemBertLayer""",
				    """RemBertModel""",
				    """RemBertPreTrainedModel""",
				    """load_tf_weights_in_rembert""",
				]


try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				snake_case_    					=	[
				    """TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """TFRemBertForCausalLM""",
				    """TFRemBertForMaskedLM""",
				    """TFRemBertForMultipleChoice""",
				    """TFRemBertForQuestionAnswering""",
				    """TFRemBertForSequenceClassification""",
				    """TFRemBertForTokenClassification""",
				    """TFRemBertLayer""",
				    """TFRemBertModel""",
				    """TFRemBertPreTrainedModel""",
				]


if TYPE_CHECKING:
				from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig

				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_rembert import RemBertTokenizer

				try:
								if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_rembert_fast import RemBertTokenizerFast

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_rembert import (
								    REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    RemBertForCausalLM,
								    RemBertForMaskedLM,
								    RemBertForMultipleChoice,
								    RemBertForQuestionAnswering,
								    RemBertForSequenceClassification,
								    RemBertForTokenClassification,
								    RemBertLayer,
								    RemBertModel,
								    RemBertPreTrainedModel,
								    load_tf_weights_in_rembert,
								)

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_rembert import (
								    TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFRemBertForCausalLM,
								    TFRemBertForMaskedLM,
								    TFRemBertForMultipleChoice,
								    TFRemBertForQuestionAnswering,
								    TFRemBertForSequenceClassification,
								    TFRemBertForTokenClassification,
								    TFRemBertLayer,
								    TFRemBertModel,
								    TFRemBertPreTrainedModel,
								)


else:
				import sys

				snake_case_    					=	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





