






'''simple docstring'''




import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
						    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
						    MODEL_MAPPING,
						    DeiTForImageClassification,
						    DeiTForImageClassificationWithTeacher,
						    DeiTForMaskedImageModeling,
						    DeiTModel,
						)
						from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import DeiTImageProcessor







class    A_	:
							"""simple docstring"""




							def __init__(		self			:Union[str, Any]       ,							lowerCAmelCase__			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]=13       ,							lowerCAmelCase__			:List[Any]=30       ,							lowerCAmelCase__			:Any=2       ,							lowerCAmelCase__			:Optional[int]=3       ,							lowerCAmelCase__			:Optional[Any]=True       ,							lowerCAmelCase__			:Dict=True       ,							lowerCAmelCase__			:Optional[Any]=32       ,							lowerCAmelCase__			:Optional[Any]=5       ,							lowerCAmelCase__			:List[str]=4       ,							lowerCAmelCase__			:Tuple=37       ,							lowerCAmelCase__			:Optional[int]="gelu"       ,							lowerCAmelCase__			:int=0.1       ,							lowerCAmelCase__			:List[Any]=0.1       ,							lowerCAmelCase__			:int=10       ,							lowerCAmelCase__			:Any=0.0_2       ,							lowerCAmelCase__			:int=3       ,							lowerCAmelCase__			:Optional[Any]=None       ,							lowerCAmelCase__			:Optional[int]=2       ,							)				->  str:


										'''simple docstring'''




										snake_case_				:					Optional[int]   =       parent
										snake_case_				:					int   =       batch_size
										snake_case_				:					Any   =       image_size
										snake_case_				:					List[Any]   =       patch_size
										snake_case_				:					Tuple   =       num_channels
										snake_case_				:					Optional[int]   =       is_training
										snake_case_				:					Any   =       use_labels
										snake_case_				:					Optional[Any]   =       hidden_size
										snake_case_				:					Any   =       num_hidden_layers
										snake_case_				:					Any   =       num_attention_heads
										snake_case_				:					Tuple   =       intermediate_size
										snake_case_				:					Dict   =       hidden_act
										snake_case_				:					Any   =       hidden_dropout_prob
										snake_case_				:					List[str]   =       attention_probs_dropout_prob
										snake_case_				:					Tuple   =       type_sequence_label_size
										snake_case_				:					Any   =       initializer_range
										snake_case_				:					List[str]   =       scope
										snake_case_				:					Union[str, Any]   =       encoder_stride

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

							def 							_A	(		self			:Any				)				->  List[str]:


										'''simple docstring'''




										snake_case_				:					List[Any]   =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

										snake_case_				:					int   =       None
										if self.use_labels:
													snake_case_				:					Union[str, Any]   =       ids_tensor([self.batch_size]       ,							self.type_sequence_label_size				)

										snake_case_				:					List[str]   =       self.get_config()

										return config, pixel_values, labels

							def 							_A	(		self			:Tuple				)				->  Any:


										'''simple docstring'''




										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=_A       ,							initializer_range=self.initializer_range       ,							encoder_stride=self.encoder_stride       ,							)

							def 							_A	(		self			:str       ,							lowerCAmelCase__			:List[str]       ,							lowerCAmelCase__			:str       ,							lowerCAmelCase__			:Tuple				)				->  Dict:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       DeiTModel(config=_A				)
										model.to(_A				)
										model.eval()
										snake_case_				:					Tuple   =       model(_A				)
										self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.hidden_size)				)

							def 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Dict       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:Any				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Dict   =       DeiTForMaskedImageModeling(config=_A				)
										model.to(_A				)
										model.eval()
										snake_case_				:					List[Any]   =       model(_A				)
										self.parent.assertEqual(
										    result.reconstruction.shape       ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)				)

										# test greyscale images
										snake_case_				:					Union[str, Any]   =       1
										snake_case_				:					List[Any]   =       DeiTForMaskedImageModeling(_A				)
										model.to(_A				)
										model.eval()

										snake_case_				:					Dict   =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
										snake_case_				:					Dict   =       model(_A				)
										self.parent.assertEqual(result.reconstruction.shape       ,							(self.batch_size, 1, self.image_size, self.image_size)				)

							def 							_A	(		self			:int       ,							lowerCAmelCase__			:Dict       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:int				)				->  int:


										'''simple docstring'''




										snake_case_				:					str   =       self.type_sequence_label_size
										snake_case_				:					Optional[int]   =       DeiTForImageClassification(_A				)
										model.to(_A				)
										model.eval()
										snake_case_				:					Union[str, Any]   =       model(_A       ,							labels=_A				)
										self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)				)

										# test greyscale images
										snake_case_				:					int   =       1
										snake_case_				:					List[str]   =       DeiTForImageClassification(_A				)
										model.to(_A				)
										model.eval()

										snake_case_				:					Optional[Any]   =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
										snake_case_				:					Optional[Any]   =       model(_A       ,							labels=_A				)
										self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)				)






							def 							_A	(		self			:Optional[int]				)				->  Union[str, Any]:


										'''simple docstring'''




										snake_case_				:					Union[str, Any]   =       self.prepare_config_and_inputs()
										(
										    (
										    snake_case_						
										),	(
										    snake_case_						
										),	(
										    snake_case_						
										),							
										)				:					List[str]   =       config_and_inputs
										snake_case_				:					Optional[int]   =       {"pixel_values": pixel_values}
										return config, inputs_dict







@require_torch
class    A_	(__lowercase						,					__lowercase						,					unittest.TestCase							):
							"""simple docstring"""




							a__   		=	(
							    (
							        DeiTModel,
							        DeiTForImageClassification,
							        DeiTForImageClassificationWithTeacher,
							        DeiTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							a__   		=	(
							    {
							        '''feature-extraction''': DeiTModel,
							        '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
							    }
							    if is_torch_available()
							    else {}
							)

							a__   		=	False
							a__   		=	False
							a__   		=	False

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


										'''simple docstring'''




										snake_case_				:					List[str]   =       DeiTModelTester(self				)
										snake_case_				:					Tuple   =       ConfigTester(self       ,							config_class=_A       ,							has_text_modality=_A       ,							hidden_size=37				)

							def 							_A	(		self			:Dict				)				->  List[str]:


										'''simple docstring'''




										self.config_tester.run_common_tests()

							@unittest.skip(reason="DeiT does not use inputs_embeds"				)
							def 							_A	(		self			:List[Any]				)				->  Optional[int]:


										'''simple docstring'''




										pass

							def 							_A	(		self			:Union[str, Any]				)				->  Optional[int]:


										'''simple docstring'''




										snake_case_,	snake_case_				:					List[Any]   =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													snake_case_				:					List[Any]   =       model_class(_A				)
													self.assertIsInstance(model.get_input_embeddings()       ,							(nn.Module)				)
													snake_case_				:					Union[str, Any]   =       model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_A       ,							nn.Linear				)				)

							def 							_A	(		self			:Union[str, Any]				)				->  Tuple:


										'''simple docstring'''




										snake_case_,	snake_case_				:					int   =       self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													snake_case_				:					Any   =       model_class(_A				)
													snake_case_				:					str   =       inspect.signature(model.forward				)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													snake_case_				:					List[str]   =       [*signature.parameters.keys()]

													snake_case_				:					int   =       ["pixel_values"]
													self.assertListEqual(arg_names[:1]       ,							_A				)

							def 							_A	(		self			:Dict				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					int   =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_A				)

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


										'''simple docstring'''




										snake_case_				:					Tuple   =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*_A				)

							def 							_A	(		self			:Optional[int]				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Tuple   =       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_A				)

							def 							_A	(		self			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:List[Any]       ,							lowerCAmelCase__			:Any=False				)				->  List[str]:


										'''simple docstring'''




										snake_case_				:					Any   =       super()._prepare_for_class(_A       ,							_A       ,							return_labels=_A				)

										if return_labels:
													if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
																del inputs_dict["labels"]

										return inputs_dict

							def 							_A	(		self			:str				)				->  Dict:


										'''simple docstring'''




										if not self.model_tester.is_training:
													return

										snake_case_,	snake_case_				:					int   =       self.model_tester.prepare_config_and_inputs_for_common()
										snake_case_				:					Optional[int]   =       True

										for model_class in self.all_model_classes:
													# DeiTForImageClassificationWithTeacher supports inference-only
													if (
													    model_class in get_values(_A				)
													    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
													):
																continue
													snake_case_				:					List[Any]   =       model_class(_A				)
													model.to(_A				)
													model.train()
													snake_case_				:					Tuple   =       self._prepare_for_class(_A       ,							_A       ,							return_labels=_A				)
													snake_case_				:					Optional[int]   =       model(**_A				).loss
													loss.backward()

							def 							_A	(		self			:str				)				->  Union[str, Any]:


										'''simple docstring'''




										snake_case_,	snake_case_				:					str   =       self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
													return

										snake_case_				:					int   =       False
										snake_case_				:					Dict   =       True

										for model_class in self.all_model_classes:
													if model_class in get_values(_A				) or not model_class.supports_gradient_checkpointing:
																continue
													# DeiTForImageClassificationWithTeacher supports inference-only
													if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
																continue
													snake_case_				:					Tuple   =       model_class(_A				)
													model.gradient_checkpointing_enable()
													model.to(_A				)
													model.train()
													snake_case_				:					List[str]   =       self._prepare_for_class(_A       ,							_A       ,							return_labels=_A				)
													snake_case_				:					Optional[int]   =       model(**_A				).loss
													loss.backward()

							def 							_A	(		self			:List[str]				)				->  int:


										'''simple docstring'''




										snake_case_,	snake_case_				:					int   =       self.model_tester.prepare_config_and_inputs_for_common()

										snake_case_				:					Optional[Any]   =       [
										    {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
										    {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
										    {"title": "regression", "num_labels": 1, "dtype": torch.float},
										]

										for model_class in self.all_model_classes:
													if (
													    model_class
													    not in [
													        *get_values(_A				),
													        *get_values(_A				),
													    ]
													    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
													):
																continue

													for problem_type in problem_types:
																with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}'''				):
																			snake_case_				:					Union[str, Any]   =       problem_type["title"]
																			snake_case_				:					List[str]   =       problem_type["num_labels"]

																			snake_case_				:					str   =       model_class(_A				)
																			model.to(_A				)
																			model.train()

																			snake_case_				:					Dict   =       self._prepare_for_class(_A       ,							_A       ,							return_labels=_A				)

																			if problem_type["num_labels"] > 1:
																						snake_case_				:					List[Any]   =       inputs["labels"].unsqueeze(1				).repeat(1       ,							problem_type["num_labels"]				)

																			snake_case_				:					List[Any]   =       inputs["labels"].to(problem_type["dtype"]				)

																			# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																			# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																			# they have the same size." which is a symptom something in wrong for the regression problem.
																			# See https://github.com/huggingface/transformers/issues/11780
																			with warnings.catch_warnings(record=_A				) as warning_list:
																						snake_case_				:					Union[str, Any]   =       model(**_A				).loss
																			for w in warning_list:
																						if "Using a target size that is different to the input size" in str(w.message				):
																									raise ValueError(
																									    F'''Something is going wrong in the regression problem: intercepted {w.message}'''				)

																			loss.backward()






							@slow
							def 							_A	(		self			:List[Any]				)				->  Union[str, Any]:


										'''simple docstring'''




										for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													snake_case_				:					Optional[Any]   =       DeiTModel.from_pretrained(_A				)
													self.assertIsNotNone(_A				)

def 	__UpperCAmelCase       ( )->    int:



			"""simple docstring"""



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







@require_torch
@require_vision
class    A_	(unittest.TestCase							):
							"""simple docstring"""




							@cached_property
							def 							_A	(		self			:int				)				->  str:


										'''simple docstring'''




										return (
										    DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224"				)
										    if is_vision_available()
										    else None
										)

							@slow
							def 							_A	(		self			:Any				)				->  List[str]:


										'''simple docstring'''




										snake_case_				:					str   =       DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"				).to(
										    _A				)

										snake_case_				:					List[Any]   =       self.default_image_processor
										snake_case_				:					Any   =       prepare_img()
										snake_case_				:					Tuple   =       image_processor(images=_A       ,							return_tensors="pt"				).to(_A				)

										# forward pass
										with torch.no_grad():
													snake_case_				:					List[str]   =       model(**_A				)

										# verify the logits
										snake_case_				:					Tuple   =       torch.Size((1, 1_000)				)
										self.assertEqual(outputs.logits.shape       ,							_A				)

										snake_case_				:					str   =       torch.tensor([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1]				).to(_A				)

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






							@slow
							@require_accelerate
							@require_torch_gpu
							def 							_A	(		self			:int				)				->  Dict:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       DeiTModel.from_pretrained(
										    "facebook/deit-base-distilled-patch16-224"       ,							torch_dtype=torch.floataa       ,							device_map="auto"				)
										snake_case_				:					Optional[int]   =       self.default_image_processor

										snake_case_				:					Union[str, Any]   =       prepare_img()
										snake_case_				:					Optional[Any]   =       image_processor(images=_A       ,							return_tensors="pt"				)
										snake_case_				:					Dict   =       inputs.pixel_values.to(_A				)

										# forward pass to make sure inference works in fp16
										with torch.no_grad():
													snake_case_				:					List[str]   =       model(_A				)












'''simple docstring'''




from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCamelCase   :					List[str]   							=					logging.get_logger(__name__)

__lowerCamelCase   :					int   							=					{
    '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''',
    # See all Cvt models at https://huggingface.co/models?filter=cvt
}







class    A_	(a_							):
							"""simple docstring"""




							a__   		=	'''cvt'''

							def __init__(		self			:List[Any]       ,							lowerCAmelCase__			:Optional[int]=3       ,							lowerCAmelCase__			:Any=[7, 3, 3]       ,							lowerCAmelCase__			:Dict=[4, 2, 2]       ,							lowerCAmelCase__			:Union[str, Any]=[2, 1, 1]       ,							lowerCAmelCase__			:Any=[64, 192, 384]       ,							lowerCAmelCase__			:List[str]=[1, 3, 6]       ,							lowerCAmelCase__			:str=[1, 2, 10]       ,							lowerCAmelCase__			:Any=[4.0, 4.0, 4.0]       ,							lowerCAmelCase__			:int=[0.0, 0.0, 0.0]       ,							lowerCAmelCase__			:Optional[Any]=[0.0, 0.0, 0.0]       ,							lowerCAmelCase__			:Dict=[0.0, 0.0, 0.1]       ,							lowerCAmelCase__			:List[Any]=[True, True, True]       ,							lowerCAmelCase__			:List[Any]=[False, False, True]       ,							lowerCAmelCase__			:Dict=["dw_bn", "dw_bn", "dw_bn"]       ,							lowerCAmelCase__			:Any=[3, 3, 3]       ,							lowerCAmelCase__			:Tuple=[1, 1, 1]       ,							lowerCAmelCase__			:Optional[int]=[2, 2, 2]       ,							lowerCAmelCase__			:Union[str, Any]=[1, 1, 1]       ,							lowerCAmelCase__			:Any=[1, 1, 1]       ,							lowerCAmelCase__			:List[str]=0.0_2       ,							lowerCAmelCase__			:Dict=1E-1_2       ,							**lowerCAmelCase__			:Optional[Any]       ,							)				->  str:


										'''simple docstring'''




										super().__init__(**lowerCAmelCase__				)
										snake_case_				:					int   =       num_channels
										snake_case_				:					int   =       patch_sizes
										snake_case_				:					Optional[Any]   =       patch_stride
										snake_case_				:					Dict   =       patch_padding
										snake_case_				:					Tuple   =       embed_dim
										snake_case_				:					Optional[int]   =       num_heads
										snake_case_				:					Union[str, Any]   =       depth
										snake_case_				:					Optional[int]   =       mlp_ratio
										snake_case_				:					Tuple   =       attention_drop_rate
										snake_case_				:					str   =       drop_rate
										snake_case_				:					Tuple   =       drop_path_rate
										snake_case_				:					Any   =       qkv_bias
										snake_case_				:					Union[str, Any]   =       cls_token
										snake_case_				:					int   =       qkv_projection_method
										snake_case_				:					Any   =       kernel_qkv
										snake_case_				:					Union[str, Any]   =       padding_kv
										snake_case_				:					str   =       stride_kv
										snake_case_				:					Dict   =       padding_q
										snake_case_				:					Tuple   =       stride_q
										snake_case_				:					Any   =       initializer_range
										snake_case_				:					Any   =       layer_norm_eps




