


'''simple docstring'''

import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch
	from torch import nn

	from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
	from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image


class       a__				:







				"""simple docstring"""



				def __init__(self       ,			__lowercase       ,			__lowercase=13       ,			__lowercase=64       ,			__lowercase=2       ,			__lowercase=3       ,			__lowercase=True       ,			__lowercase=True       ,			__lowercase=32       ,			__lowercase=5       ,			__lowercase=4       ,			__lowercase=37       ,			__lowercase="gelu"       ,			__lowercase=0.1       ,			__lowercase=0.1       ,			__lowercase=10       ,			__lowercase=0.0_2       ,			__lowercase=[1, 16, 4, 4]       ,			__lowercase=None       ,			):
										__lowerCAmelCase							       =				parent
										__lowerCAmelCase							       =				batch_size
										__lowerCAmelCase							       =				image_size
										__lowerCAmelCase							       =				patch_size
										__lowerCAmelCase							       =				num_channels
										__lowerCAmelCase							       =				is_training
										__lowerCAmelCase							       =				use_labels
										__lowerCAmelCase							       =				hidden_size
										__lowerCAmelCase							       =				num_hidden_layers
										__lowerCAmelCase							       =				num_attention_heads
										__lowerCAmelCase							       =				intermediate_size
										__lowerCAmelCase							       =				hidden_act
										__lowerCAmelCase							       =				hidden_dropout_prob
										__lowerCAmelCase							       =				attention_probs_dropout_prob
										__lowerCAmelCase							       =				type_sequence_label_size
										__lowerCAmelCase							       =				initializer_range
										__lowerCAmelCase							       =				scope
										__lowerCAmelCase							       =				backbone_featmap_shape

										# in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										# the number of patches is based on the feature map of the backbone, which by default uses an output stride
										# of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
										__lowerCAmelCase							       =				(self.image_size // 32) ** 2
										__lowerCAmelCase							       =				num_patches + 1




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

										__lowerCAmelCase							       =				self.get_config()

										return config, pixel_values, labels




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				{
										    '''global_padding''': '''same''',
										    '''layer_type''': '''bottleneck''',
										    '''depths''': [3, 4, 9],
										    '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
										    '''embedding_dynamic_padding''': True,
										    '''hidden_sizes''': [4, 8, 16, 32],
										    '''num_groups''': 2,
										}

										return ViTHybridConfig(
										    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       ,			backbone_featmap_shape=self.backbone_featmap_shape       ,			backbone_config=__lowercase       ,			)




				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase		):
										__lowerCAmelCase							       =				ViTHybridModel(config=__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				model(__lowercase		)
										self.parent.assertEqual(result.last_hidden_state.shape       ,			(self.batch_size, self.seq_length, self.hidden_size)		)




				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase		):
										__lowerCAmelCase							       =				self.type_sequence_label_size
										__lowerCAmelCase							       =				ViTHybridForImageClassification(__lowercase		)
										model.to(__lowercase		)
										model.eval()
										__lowerCAmelCase							       =				model(__lowercase       ,			labels=__lowercase		)
										self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.type_sequence_label_size)		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.prepare_config_and_inputs()
										__lowerCAmelCase       ,					__lowerCAmelCase       ,					__lowerCAmelCase							       =				config_and_inputs
										__lowerCAmelCase							       =				{'''pixel_values''': pixel_values}
										return config, inputs_dict


@require_torch
class       a__				( __A							,						__A							,						unittest.TestCase      ):







				"""simple docstring"""



				__UpperCamelCase    :		List[str]	=	(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
				__UpperCamelCase    :		List[Any]	=	(
				    {'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification}
				    if is_torch_available()
				    else {}
				)
				__UpperCamelCase    :		Dict	=	False
				__UpperCamelCase    :		int	=	False
				__UpperCamelCase    :		Union[str, Any]	=	False




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ViTHybridModelTester(self		)
										__lowerCAmelCase							       =				ConfigTester(self       ,			config_class=__lowercase       ,			has_text_modality=__lowercase       ,			hidden_size=37		)




				def 					_snake_case  (self		):
										self.config_tester.run_common_tests()




				@unittest.skip(reason='''ViT does not use inputs_embeds'''		)
				def 					_snake_case  (self		):
										pass




				def 					_snake_case  (self		):
										__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																__lowerCAmelCase							       =				model_class(__lowercase		)
																self.assertIsInstance(model.get_input_embeddings()       ,			(nn.Module)		)
																__lowerCAmelCase							       =				model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(__lowercase       ,			nn.Linear		)		)




				def 					_snake_case  (self		):
										__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs_for_common()

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

																__lowerCAmelCase							       =				['''pixel_values''']
																self.assertListEqual(arg_names[:1]       ,			__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowercase		)




				def 					_snake_case  (self		):
										__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.model_tester.prepare_config_and_inputs_for_common()

										__lowerCAmelCase							       =				_config_zero_init(__lowercase		)
										for model_class in self.all_model_classes:
																__lowerCAmelCase							       =				model_class(config=__lowercase		)
																# Skip the check for the backbone
																for name, module in model.named_modules():
																						if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
																												__lowerCAmelCase							       =				[F"""{name}.{key}""" for key in module.state_dict().keys()]
																												break

																for name, param in model.named_parameters():
																						if param.requires_grad:
																												if name in backbone_params:
																																		continue
																												self.assertIn(
																												    ((param.data.mean() * 1e9).round() / 1e9).item()       ,			[0.0, 1.0]       ,			msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""       ,			)




				@slow
				def 					_snake_case  (self		):
										for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__lowerCAmelCase							       =				ViTHybridModel.from_pretrained(__lowercase		)
																self.assertIsNotNone(__lowercase		)

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




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







				"""simple docstring"""



				@cached_property
				def 					_snake_case  (self		):
										return (
										    ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
										    if is_vision_available()
										    else None
										)




				@slow
				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(
										    __lowercase		)

										__lowerCAmelCase							       =				self.default_image_processor
										__lowerCAmelCase							       =				prepare_img()
										__lowerCAmelCase							       =				image_processor(images=__lowercase       ,			return_tensors='''pt'''		).to(__lowercase		)

										# forward pass
										with torch.no_grad():
																__lowerCAmelCase							       =				model(**__lowercase		)

										# verify the logits
										__lowerCAmelCase							       =				torch.Size((1, 10_00)		)
										self.assertEqual(outputs.logits.shape       ,			__lowercase		)

										__lowerCAmelCase							       =				torch.tensor([-1.9_0_9_0, -0.4_9_9_3, -0.2_3_8_9]		).to(__lowercase		)

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




				@slow
				@require_accelerate
				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384'''		)
										__lowerCAmelCase							       =				ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384'''       ,			device_map='''auto'''		)

										__lowerCAmelCase							       =				prepare_img()

										__lowerCAmelCase							       =				image_processor(images=__lowercase       ,			return_tensors='''pt'''		)
										__lowerCAmelCase							       =				model(**__lowercase		)
										__lowerCAmelCase							       =				outputs.logits
										# model predicts one of the 1000 ImageNet classes
										__lowerCAmelCase							       =				logits.argmax(-1		).item()

										self.assertTrue(model.config.idalabel[predicted_class_idx]       ,			'''tabby, tabby cat'''		)





'''simple docstring'''

from __future__ import annotations

def 							__magic_name__(						lowerCamelCase,				lowerCamelCase):
						__lowerCAmelCase							       =				sorted(numsa + numsa)
						__lowerCAmelCase       ,					__lowerCAmelCase							       =				divmod(len(lowerCamelCase),				2)
						if mod == 1:
												return all_numbers[div]
						else:
												return (all_numbers[div] + all_numbers[div - 1]) / 2


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	_UpperCAmelCase				: Union[str, Any]							    =				[float(x) for x in input("""Enter the elements of first array: """).split()]
	_UpperCAmelCase				: int							    =				[float(x) for x in input("""Enter the elements of second array: """).split()]
	print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")

