






import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, 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 transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
	from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import MobileViTImageProcessor



class 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_		):





					"""simple docstring"""






					def  _lowercase  (      self  :						Optional[Any] ):
						snake_case__				:   List[str]     =						self.config_class(**self.inputs_dict )
						self.parent.assertTrue(hasattr(__A							,	"hidden_sizes" ) )
						self.parent.assertTrue(hasattr(__A							,	"neck_hidden_sizes" ) )
						self.parent.assertTrue(hasattr(__A							,	"num_attention_heads" ) )



class 							SCREAMING_SNAKE_CASE__		:





					"""simple docstring"""






					def __init__(      self  :						Optional[int]							,	__A  :						Dict							,	__A  :						Any=1_3							,	__A  :						Optional[int]=3_2							,	__A  :						List[Any]=2							,	__A  :						Dict=3							,	__A  :						Optional[Any]=6_4_0							,	__A  :						Any=4							,	__A  :						Dict="silu"							,	__A  :						Union[str, Any]=3							,	__A  :						Tuple=3_2							,	__A  :						Tuple=0.1							,	__A  :						Any=0.1							,	__A  :						Dict=0.1							,	__A  :						Dict=0.0_2							,	__A  :						Any=True							,	__A  :						Optional[int]=True							,	__A  :						str=1_0							,	__A  :						List[str]=None							,	):
						snake_case__				:   Optional[int]     =						parent
						snake_case__				:   List[str]     =						batch_size
						snake_case__				:   Dict     =						image_size
						snake_case__				:   Dict     =						patch_size
						snake_case__				:   Optional[Any]     =						num_channels
						snake_case__				:   Dict     =						last_hidden_size
						snake_case__				:   Any     =						num_attention_heads
						snake_case__				:   Union[str, Any]     =						hidden_act
						snake_case__				:   Any     =						conv_kernel_size
						snake_case__				:   int     =						output_stride
						snake_case__				:   Optional[Any]     =						hidden_dropout_prob
						snake_case__				:   List[str]     =						attention_probs_dropout_prob
						snake_case__				:   Any     =						classifier_dropout_prob
						snake_case__				:   Any     =						use_labels
						snake_case__				:   List[Any]     =						is_training
						snake_case__				:   str     =						num_labels
						snake_case__				:   List[str]     =						initializer_range
						snake_case__				:   Tuple     =						scope



					def  _lowercase  (      self  :						List[str] ):
						snake_case__				:   List[Any]     =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

						snake_case__				:   Optional[Any]     =						None
						snake_case__				:   Union[str, Any]     =						None
						if self.use_labels:
							snake_case__				:   Tuple     =						ids_tensor([self.batch_size]							,	self.num_labels )
							snake_case__				:   List[str]     =						ids_tensor([self.batch_size, self.image_size, self.image_size]							,	self.num_labels )

						snake_case__				:   str     =						self.get_config()

						return config, pixel_values, labels, pixel_labels



					def  _lowercase  (      self  :						Optional[Any] ):
						return MobileViTConfig(
						    image_size=self.image_size							,	patch_size=self.patch_size							,	num_channels=self.num_channels							,	num_attention_heads=self.num_attention_heads							,	hidden_act=self.hidden_act							,	conv_kernel_size=self.conv_kernel_size							,	output_stride=self.output_stride							,	hidden_dropout_prob=self.hidden_dropout_prob							,	attention_probs_dropout_prob=self.attention_probs_dropout_prob							,	classifier_dropout_prob=self.classifier_dropout_prob							,	initializer_range=self.initializer_range							,	)



					def  _lowercase  (      self  :						Any							,	__A  :						List[Any]							,	__A  :						Any							,	__A  :						List[Any]							,	__A  :						Union[str, Any] ):
						snake_case__				:   List[str]     =						MobileViTModel(config=__A )
						model.to(__A )
						model.eval()
						snake_case__				:   Any     =						model(__A )
						self.parent.assertEqual(
						    result.last_hidden_state.shape							,	(
						        self.batch_size,
						        self.last_hidden_size,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,	)



					def  _lowercase  (      self  :						Optional[Any]							,	__A  :						int							,	__A  :						str							,	__A  :						Optional[Any]							,	__A  :						Any ):
						snake_case__				:   Union[str, Any]     =						self.num_labels
						snake_case__				:   Any     =						MobileViTForImageClassification(__A )
						model.to(__A )
						model.eval()
						snake_case__				:   List[Any]     =						model(__A							,	labels=__A )
						self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.num_labels) )



					def  _lowercase  (      self  :						List[Any]							,	__A  :						Optional[int]							,	__A  :						Union[str, Any]							,	__A  :						Dict							,	__A  :						Optional[Any] ):
						snake_case__				:   Optional[int]     =						self.num_labels
						snake_case__				:   str     =						MobileViTForSemanticSegmentation(__A )
						model.to(__A )
						model.eval()
						snake_case__				:   List[str]     =						model(__A )
						self.parent.assertEqual(
						    result.logits.shape							,	(
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,	)
						snake_case__				:   List[str]     =						model(__A							,	labels=__A )
						self.parent.assertEqual(
						    result.logits.shape							,	(
						        self.batch_size,
						        self.num_labels,
						        self.image_size // self.output_stride,
						        self.image_size // self.output_stride,
						    )							,	)






					def  _lowercase  (      self  :						Optional[int] ):
						snake_case__				:   str     =						self.prepare_config_and_inputs()
						snake_case__,		snake_case__,		snake_case__,		snake_case__				:   Optional[int]     =						config_and_inputs
						snake_case__				:   List[str]     =						{"pixel_values": pixel_values}
						return config, inputs_dict



@require_torch
class 							SCREAMING_SNAKE_CASE__		(       UpperCamelCase_				,     UpperCamelCase_				,     unittest.TestCase		):





					"""simple docstring"""






					a_			=	(
					    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)
					a_			=	(
					    {
					        "feature-extraction": MobileViTModel,
					        "image-classification": MobileViTForImageClassification,
					        "image-segmentation": MobileViTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					a_			=	False
					a_			=	False
					a_			=	False
					a_			=	False



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   List[str]     =						MobileViTModelTester(self )
						snake_case__				:   Tuple     =						MobileViTConfigTester(self							,	config_class=__A							,	has_text_modality=__A )



					def  _lowercase  (      self  :						Optional[Any] ):
						self.config_tester.run_common_tests()



					@unittest.skip(reason="MobileViT does not use inputs_embeds" )
					def  _lowercase  (      self  :						Union[str, Any] ):
						pass



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



					@unittest.skip(reason="MobileViT does not output attentions" )
					def  _lowercase  (      self  :						int ):
						pass



					def  _lowercase  (      self  :						Any ):
						snake_case__,		snake_case__				:   Dict     =						self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__				:   List[Any]     =						["pixel_values"]
							self.assertListEqual(arg_names[:1]							,	__A )



					@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
					def  _lowercase  (      self  :						Tuple ):
						pass



					def  _lowercase  (      self  :						List[Any] ):
						snake_case__				:   List[str]     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__A )



					def  _lowercase  (      self  :						List[str] ):
						def check_hidden_states_output(__A  :						Any							,	__A  :						Any							,	__A  :						Optional[Any] ):
							snake_case__				:   List[Any]     =						model_class(__A )
							model.to(__A )
							model.eval()

							with torch.no_grad():
								snake_case__				:   Any     =						model(**self._prepare_for_class(__A							,	__A ) )

							snake_case__				:   int     =						outputs.hidden_states

							snake_case__				:   Any     =						5
							self.assertEqual(len(__A )							,	__A )

							# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
							# with the width and height being successively divided by 2.
							snake_case__				:   Dict     =						2
							for i in range(len(__A ) ):
								self.assertListEqual(
								    list(hidden_states[i].shape[-2:] )							,	[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]							,	)
								divisor *= 2

							self.assertEqual(self.model_tester.output_stride							,	divisor // 2 )

						snake_case__,		snake_case__				:   Optional[Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							snake_case__				:   Optional[int]     =						True
							check_hidden_states_output(__A							,	__A							,	__A )

							# check that output_hidden_states also work using config
							del inputs_dict["output_hidden_states"]
							snake_case__				:   List[Any]     =						True

							check_hidden_states_output(__A							,	__A							,	__A )



					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Union[str, Any]     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__A )



					def  _lowercase  (      self  :						List[Any] ):
						snake_case__				:   str     =						self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*__A )






					@slow
					def  _lowercase  (      self  :						Union[str, Any] ):
						for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__				:   Optional[int]     =						MobileViTModel.from_pretrained(__A )
							self.assertIsNotNone(__A )







def   SCREAMING_SNAKE_CASE       (				):
	snake_case__				:   Any     =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
	return image





@require_torch
@require_vision
class 							SCREAMING_SNAKE_CASE__		(       unittest.TestCase		):





					"""simple docstring"""






					@cached_property
					def  _lowercase  (      self  :						Any ):
						return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None



					@slow
					def  _lowercase  (      self  :						Union[str, Any] ):
						snake_case__				:   Dict     =						MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(__A )

						snake_case__				:   Dict     =						self.default_image_processor
						snake_case__				:   Union[str, Any]     =						prepare_img()
						snake_case__				:   int     =						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__				:   Any     =						torch.Size((1, 1_0_0_0) )
						self.assertEqual(outputs.logits.shape							,	__A )

						snake_case__				:   Dict     =						torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(__A )

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



					@slow
					def  _lowercase  (      self  :						str ):
						snake_case__				:   Tuple     =						MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
						snake_case__				:   Dict     =						model.to(__A )

						snake_case__				:   Union[str, Any]     =						MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

						snake_case__				:   Optional[Any]     =						prepare_img()
						snake_case__				:   Dict     =						image_processor(images=__A							,	return_tensors="pt" ).to(__A )

						# forward pass
						with torch.no_grad():
							snake_case__				:   Optional[int]     =						model(**__A )
						snake_case__				:   int     =						outputs.logits

						# verify the logits
						snake_case__				:   Tuple     =						torch.Size((1, 2_1, 3_2, 3_2) )
						self.assertEqual(logits.shape							,	__A )

						snake_case__				:   int     =						torch.tensor(
						    [
						        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
						        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
						        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
						    ]							,	device=__A							,	)

						self.assertTrue(torch.allclose(logits[0, :3, :3, :3]							,	__A							,	atol=1e-4 ) )






					@slow
					def  _lowercase  (      self  :						Any ):
						snake_case__				:   Optional[int]     =						MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
						snake_case__				:   Optional[Any]     =						model.to(__A )

						snake_case__				:   int     =						MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )

						snake_case__				:   Tuple     =						prepare_img()
						snake_case__				:   int     =						image_processor(images=__A							,	return_tensors="pt" ).to(__A )

						# forward pass
						with torch.no_grad():
							snake_case__				:   Any     =						model(**__A )

						snake_case__				:   str     =						outputs.logits.detach().cpu()

						snake_case__				:   List[str]     =						image_processor.post_process_semantic_segmentation(outputs=__A							,	target_sizes=[(5_0, 6_0)] )
						snake_case__				:   Optional[int]     =						torch.Size((5_0, 6_0) )
						self.assertEqual(segmentation[0].shape							,	__A )

						snake_case__				:   List[Any]     =						image_processor.post_process_semantic_segmentation(outputs=__A )
						snake_case__				:   int     =						torch.Size((3_2, 3_2) )
						self.assertEqual(segmentation[0].shape							,	__A )











import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier







def   SCREAMING_SNAKE_CASE       (				snake_case_      :							dict     ):
	return (data["data"], data["target"])







def   SCREAMING_SNAKE_CASE       (				snake_case_      :							np.ndarray  ,						snake_case_      :							np.ndarray     ):
	snake_case__				:   Optional[int]     =						XGBClassifier()
	classifier.fit(snake_case_  ,						snake_case_     )
	return classifier







def   SCREAMING_SNAKE_CASE       (				):
	snake_case__				:   Any     =						load_iris()
	snake_case__,		snake_case__				:   str     =						data_handling(snake_case_     )
	snake_case__,		snake_case__,		snake_case__,		snake_case__				:   int     =						train_test_split(
	    snake_case_  ,						snake_case_  ,						test_size=0.25     )

	snake_case__				:   Dict     =						iris["target_names"]

	# Create an XGBoost Classifier from the training data
	snake_case__				:   Dict     =						xgboost(snake_case_  ,						snake_case_     )

	# Display the confusion matrix of the classifier with both training and test sets
	ConfusionMatrixDisplay.from_estimator(
	    snake_case_  ,						snake_case_  ,						snake_case_  ,						display_labels=snake_case_  ,						cmap="Blues"  ,						normalize="true"  ,						)
	plt.title("Normalized Confusion Matrix - IRIS Dataset"     )
	plt.show()


if __name__ == "__main__":
	import doctest

	doctest.testmod(verbose=True)
	main()



