



import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
							from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor







class     __lowerCAmelCase					:



			def __init__(		self     :						Any				,	A     :						Any				,	A     :						Any=3				,	A     :						Optional[Any]=32				,	A     :						str=3				,	A     :						Optional[Any]=10				,	A     :						str=[10, 20, 30, 40]				,	A     :						int=[1, 1, 2, 1]				,	A     :						Optional[Any]=True				,	A     :						Tuple=True				,	A     :						Any="relu"				,	A     :						Union[str, Any]=3				,	A     :						List[str]=None				,	)     ->					Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase	 =     parent
						_UpperCAmelCase	 =     batch_size
						_UpperCAmelCase	 =     image_size
						_UpperCAmelCase	 =     num_channels
						_UpperCAmelCase	 =     embeddings_size
						_UpperCAmelCase	 =     hidden_sizes
						_UpperCAmelCase	 =     depths
						_UpperCAmelCase	 =     is_training
						_UpperCAmelCase	 =     use_labels
						_UpperCAmelCase	 =     hidden_act
						_UpperCAmelCase	 =     num_labels
						_UpperCAmelCase	 =     scope
						_UpperCAmelCase	 =     len(A)



			def 					_lowerCamelCase (		self     :						str)     ->					str:



						"""simple docstring"""






						_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.num_labels)

						_UpperCAmelCase	 =     self.get_config()

						return config, pixel_values, labels



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



						"""simple docstring"""






						return RegNetConfig(
						    num_channels=self.num_channels				,	embeddings_size=self.embeddings_size				,	hidden_sizes=self.hidden_sizes				,	depths=self.depths				,	hidden_act=self.hidden_act				,	num_labels=self.num_labels				,	)



			def 					_lowerCamelCase (		self     :						Optional[int]				,	A     :						int				,	A     :						Tuple				,	A     :						str)     ->					Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase	 =     RegNetModel(config=A)
						model.to(A)
						model.eval()
						_UpperCAmelCase	 =     model(A)
						# expected last hidden states: B, C, H // 32, W // 32
						self.parent.assertEqual(
						    result.last_hidden_state.shape				,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,	)



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



						"""simple docstring"""






						_UpperCAmelCase	 =     self.num_labels
						_UpperCAmelCase	 =     RegNetForImageClassification(A)
						model.to(A)
						model.eval()
						_UpperCAmelCase	 =     model(A				,	labels=A)
						self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.num_labels))



			def 					_lowerCamelCase (		self     :						Any)     ->					List[Any]:



						"""simple docstring"""






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







@require_torch
class     __lowerCAmelCase					(    A       ,		A       ,		unittest.TestCase		):
			UpperCamelCase           =  (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
			UpperCamelCase           =  (
			    {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase           =  False
			UpperCamelCase           =  False
			UpperCamelCase           =  False
			UpperCamelCase           =  False



			def 					_lowerCamelCase (		self     :						Dict)     ->					int:



						"""simple docstring"""






						_UpperCAmelCase	 =     RegNetModelTester(self)
						_UpperCAmelCase	 =     ConfigTester(self				,	config_class=A				,	has_text_modality=A)



			def 					_lowerCamelCase (		self     :						Tuple)     ->					Optional[int]:



						"""simple docstring"""






						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()



			def 					_lowerCamelCase (		self     :						Optional[int])     ->					str:



						"""simple docstring"""






						return



			@unittest.skip(reason='RegNet does not use inputs_embeds')
			def 					_lowerCamelCase (		self     :						Dict)     ->					int:



						"""simple docstring"""






						pass



			@unittest.skip(reason='RegNet does not support input and output embeddings')
			def 					_lowerCamelCase (		self     :						int)     ->					str:



						"""simple docstring"""






						pass



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



						"""simple docstring"""






						_UpperCAmelCase ,  _UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs_for_common()

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

									_UpperCAmelCase	 =     ['pixel_values']
									self.assertListEqual(arg_names[:1]				,	A)



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



						"""simple docstring"""






						_UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A)



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



						"""simple docstring"""






						_UpperCAmelCase ,  _UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									_UpperCAmelCase	 =     model_class(config=A)
									for name, module in model.named_modules():
												if isinstance(A				,	(nn.BatchNormad, nn.GroupNorm)):
															self.assertTrue(
															    torch.all(module.weight == 1)				,	msg=F"Parameter {name} of model {model_class} seems not properly initialized"				,	)
															self.assertTrue(
															    torch.all(module.bias == 0)				,	msg=F"Parameter {name} of model {model_class} seems not properly initialized"				,	)



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



						"""simple docstring"""






						def check_hidden_states_output(A     :						Optional[Any]				,	A     :						int				,	A     :						Union[str, Any]):
									_UpperCAmelCase	 =     model_class(A)
									model.to(A)
									model.eval()

									with torch.no_grad():
												_UpperCAmelCase	 =     model(**self._prepare_for_class(A				,	A))

									_UpperCAmelCase	 =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									_UpperCAmelCase	 =     self.model_tester.num_stages
									self.assertEqual(len(A)				,	expected_num_stages + 1)

									# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
									self.assertListEqual(
									    list(hidden_states[0].shape[-2:])				,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,	)

						_UpperCAmelCase ,  _UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs_for_common()
						_UpperCAmelCase	 =     ['basic', 'bottleneck']
						for model_class in self.all_model_classes:
									for layer_type in layers_type:
												_UpperCAmelCase	 =     layer_type
												_UpperCAmelCase	 =     True
												check_hidden_states_output(A				,	A				,	A)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												_UpperCAmelCase	 =     True

												check_hidden_states_output(A				,	A				,	A)



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



						"""simple docstring"""






						_UpperCAmelCase	 =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A)



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



						"""simple docstring"""






						for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									_UpperCAmelCase	 =     RegNetModel.from_pretrained(A)
									self.assertIsNotNone(A)





def 							A			(  )       ->				Any:







			'''simple docstring'''
			_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
			return image







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



			@cached_property
			def 					_lowerCamelCase (		self     :						Any)     ->					str:



						"""simple docstring"""






						return (
						    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
						    if is_vision_available()
						    else None
						)



			@slow
			def 					_lowerCamelCase (		self     :						Tuple)     ->					Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase	 =     RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(A)

						_UpperCAmelCase	 =     self.default_image_processor
						_UpperCAmelCase	 =     prepare_img()
						_UpperCAmelCase	 =     image_processor(images=A				,	return_tensors='pt').to(A)

						# forward pass
						with torch.no_grad():
									_UpperCAmelCase	 =     model(**A)

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

						_UpperCAmelCase	 =     torch.tensor([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]).to(A)

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





import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
							from PIL import Image
else:







							class     __lowerCAmelCase					:



										@staticmethod
										def 					_lowerCamelCase (		*A     :						Union[str, Any]				,	**A     :						List[Any])     ->					Union[str, Any]:



													"""simple docstring"""






													pass







@is_pipeline_test
@require_vision
class     __lowerCAmelCase					(    unittest.TestCase		):



			@require_torch
			def 					_lowerCamelCase (		self     :						List[str])     ->					Tuple:



						"""simple docstring"""






						_UpperCAmelCase	 =     pipeline(
						    model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'				,	)
						_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
						_UpperCAmelCase	 =     image_classifier(A				,	candidate_labels=['a', 'b', 'c'])

						# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
						# python and torch versions.
						self.assertIn(
						    nested_simplify(A)				,	[
						        [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}],
						        [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'c'}, {'score': 0.3_3_3, 'label': 'b'}],
						    ]				,	)

						_UpperCAmelCase	 =     image_classifier([image] * 5				,	candidate_labels=['A', 'B', 'C']				,	batch_size=2)
						self.assertEqual(
						    nested_simplify(A)				,	[
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						    ]				,	)



			@require_tf
			def 					_lowerCamelCase (		self     :						str)     ->					Tuple:



						"""simple docstring"""






						_UpperCAmelCase	 =     pipeline(
						    model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification'				,	framework='tf')
						_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
						_UpperCAmelCase	 =     image_classifier(A				,	candidate_labels=['a', 'b', 'c'])

						self.assertEqual(
						    nested_simplify(A)				,	[{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}]				,	)

						_UpperCAmelCase	 =     image_classifier([image] * 5				,	candidate_labels=['A', 'B', 'C']				,	batch_size=2)
						self.assertEqual(
						    nested_simplify(A)				,	[
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						        [
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						            {'score': 0.3_3_3, 'label': ANY(A)},
						        ],
						    ]				,	)



			@slow
			@require_torch
			def 					_lowerCamelCase (		self     :						Tuple)     ->					Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase	 =     pipeline(
						    task='zero-shot-image-classification'				,	model='openai/clip-vit-base-patch32'				,	)
						# This is an image of 2 cats with remotes and no planes
						_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
						_UpperCAmelCase	 =     image_classifier(A				,	candidate_labels=['cat', 'plane', 'remote'])

						self.assertEqual(
						    nested_simplify(A)				,	[
						        {'score': 0.5_1_1, 'label': 'remote'},
						        {'score': 0.4_8_5, 'label': 'cat'},
						        {'score': 0.0_0_4, 'label': 'plane'},
						    ]				,	)

						_UpperCAmelCase	 =     image_classifier([image] * 5				,	candidate_labels=['cat', 'plane', 'remote']				,	batch_size=2)
						self.assertEqual(
						    nested_simplify(A)				,	[
						        [
						            {'score': 0.5_1_1, 'label': 'remote'},
						            {'score': 0.4_8_5, 'label': 'cat'},
						            {'score': 0.0_0_4, 'label': 'plane'},
						        ],
						    ]
						    * 5				,	)



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



						"""simple docstring"""






						_UpperCAmelCase	 =     pipeline(
						    task='zero-shot-image-classification'				,	model='openai/clip-vit-base-patch32'				,	framework='tf')
						# This is an image of 2 cats with remotes and no planes
						_UpperCAmelCase	 =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
						_UpperCAmelCase	 =     image_classifier(A				,	candidate_labels=['cat', 'plane', 'remote'])
						self.assertEqual(
						    nested_simplify(A)				,	[
						        {'score': 0.5_1_1, 'label': 'remote'},
						        {'score': 0.4_8_5, 'label': 'cat'},
						        {'score': 0.0_0_4, 'label': 'plane'},
						    ]				,	)

						_UpperCAmelCase	 =     image_classifier([image] * 5				,	candidate_labels=['cat', 'plane', 'remote']				,	batch_size=2)
						self.assertEqual(
						    nested_simplify(A)				,	[
						        [
						            {'score': 0.5_1_1, 'label': 'remote'},
						            {'score': 0.4_8_5, 'label': 'cat'},
						            {'score': 0.0_0_4, 'label': 'plane'},
						        ],
						    ]
						    * 5				,	)
