



import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
				import jax
				import jax.numpy as jnp

				from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor

class 		UpperCAmelCase__			(			unittest.TestCase   ):




			'''simple docstring'''






			def __init__(   self							: Optional[int]       ,       a_							: Optional[int]       ,       a_							: Dict=3       ,       a_							: str=32       ,       a_							: Union[str, Any]=3       ,       a_							: Tuple=10       ,       a_							: int=[10, 20, 30, 40]       ,       a_							: Optional[Any]=[1, 1, 2, 1]       ,       a_							: Any=True       ,       a_							: Any=True       ,       a_							: Tuple="relu"       ,       a_							: int=3       ,       a_							: str=None       ,       ):
					'''simple docstring'''





					__UpperCAmelCase    :     List[Any]													=	parent
					__UpperCAmelCase    :     Tuple													=	batch_size
					__UpperCAmelCase    :     int													=	image_size
					__UpperCAmelCase    :     Union[str, Any]													=	num_channels
					__UpperCAmelCase    :     Any													=	embeddings_size
					__UpperCAmelCase    :     Any													=	hidden_sizes
					__UpperCAmelCase    :     str													=	depths
					__UpperCAmelCase    :     Dict													=	is_training
					__UpperCAmelCase    :     Optional[int]													=	use_labels
					__UpperCAmelCase    :     Union[str, Any]													=	hidden_act
					__UpperCAmelCase    :     List[str]													=	num_labels
					__UpperCAmelCase    :     str													=	scope
					__UpperCAmelCase    :     Tuple													=	len(a_ )




			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Dict													=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

					__UpperCAmelCase    :     Union[str, Any]													=	self.get_config()

					return config, pixel_values




			def  snake_case__     (   self							: List[str] ):
					'''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       ,       image_size=self.image_size       ,       )




			def  snake_case__     (   self							: int       ,       a_							: Any       ,       a_							: Optional[int] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[int]													=	FlaxRegNetModel(config=a_ )
					__UpperCAmelCase    :     Union[str, Any]													=	model(a_ )

					# Output shape (b, c, h, w)
					self.parent.assertEqual(
					    result.last_hidden_state.shape       ,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,       )




			def  snake_case__     (   self							: Dict       ,       a_							: Any       ,       a_							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Union[str, Any]													=	self.num_labels
					__UpperCAmelCase    :     str													=	FlaxRegNetForImageClassification(config=a_ )
					__UpperCAmelCase    :     Optional[int]													=	model(a_ )
					self.parent.assertEqual(result.logits.shape       ,       (self.batch_size, self.num_labels) )




			def  snake_case__     (   self							: Optional[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     str													=	self.prepare_config_and_inputs()
					__UpperCAmelCase							,					__UpperCAmelCase    :     Any													=	config_and_inputs
					__UpperCAmelCase    :     Dict													=	{'''pixel_values''': pixel_values}
					return config, inputs_dict

@require_flax
class 		UpperCAmelCase__			(			__UpperCamelCase						,unittest.TestCase   ):




			'''simple docstring'''






			UpperCamelCase									=       (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

			UpperCamelCase									=       False
			UpperCamelCase									=       False
			UpperCamelCase									=       False




			def  snake_case__     (   self							: str ):
					'''simple docstring'''





					__UpperCAmelCase    :     int													=	FlaxRegNetModelTester(self )
					__UpperCAmelCase    :     int													=	ConfigTester(self       ,       config_class=a_       ,       has_text_modality=a_ )




			def  snake_case__     (   self							: Dict ):
					'''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  snake_case__     (   self							: Tuple ):
					'''simple docstring'''





					return




			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[int]													=	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*a_ )




			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Dict													=	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*a_ )




			@unittest.skip(reason='''RegNet does not use inputs_embeds''' )
			def  snake_case__     (   self							: str ):
					'''simple docstring'''





					pass




			@unittest.skip(reason='''RegNet does not support input and output embeddings''' )
			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					pass




			def  snake_case__     (   self							: List[str] ):
					'''simple docstring'''





					__UpperCAmelCase							,					__UpperCAmelCase    :     Dict													=	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase    :     Optional[int]													=	model_class(a_ )
							__UpperCAmelCase    :     Optional[int]													=	inspect.signature(model.__call__ )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							__UpperCAmelCase    :     int													=	[*signature.parameters.keys()]

							__UpperCAmelCase    :     int													=	['''pixel_values''']
							self.assertListEqual(arg_names[:1]       ,       a_ )




			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					def check_hidden_states_output(a_							: List[Any]       ,       a_							: Optional[Any]       ,       a_							: Any ):
							__UpperCAmelCase    :     Optional[Any]													=	model_class(a_ )

							__UpperCAmelCase    :     Any													=	model(**self._prepare_for_class(a_       ,       a_ ) )

							__UpperCAmelCase    :     List[str]													=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							__UpperCAmelCase    :     Tuple													=	self.model_tester.num_stages
							self.assertEqual(len(a_ )       ,       expected_num_stages + 1 )

					__UpperCAmelCase							,					__UpperCAmelCase    :     Union[str, Any]													=	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase    :     int													=	True
							check_hidden_states_output(a_       ,       a_       ,       a_ )

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

							check_hidden_states_output(a_       ,       a_       ,       a_ )




			def  snake_case__     (   self							: Tuple ):
					'''simple docstring'''





					__UpperCAmelCase							,					__UpperCAmelCase    :     Any													=	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							with self.subTest(model_class.__name__ ):
									__UpperCAmelCase    :     Any													=	self._prepare_for_class(a_       ,       a_ )
									__UpperCAmelCase    :     Optional[int]													=	model_class(a_ )

									@jax.jit
									def model_jitted(a_							: int       ,       **a_							: int ):
											return model(pixel_values=a_       ,       **a_ )

									with self.subTest('''JIT Enabled''' ):
											__UpperCAmelCase    :     Tuple													=	model_jitted(**a_ ).to_tuple()

									with self.subTest('''JIT Disabled''' ):
											with jax.disable_jit():
													__UpperCAmelCase    :     str													=	model_jitted(**a_ ).to_tuple()

									self.assertEqual(len(a_ )       ,       len(a_ ) )
									for jitted_output, output in zip(a_       ,       a_ ):
											self.assertEqual(jitted_output.shape       ,       output.shape )

def        a						(      ):







		'''simple docstring'''





		__UpperCAmelCase    :     int													=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
		return image

@require_flax
class 		UpperCAmelCase__			(			unittest.TestCase   ):




			'''simple docstring'''






			@cached_property
			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None




			@slow
			def  snake_case__     (   self							: Optional[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     List[str]													=	FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' )

					__UpperCAmelCase    :     Tuple													=	self.default_image_processor
					__UpperCAmelCase    :     Any													=	prepare_img()
					__UpperCAmelCase    :     Any													=	image_processor(images=a_       ,       return_tensors='''np''' )

					__UpperCAmelCase    :     List[str]													=	model(**a_ )

					# verify the logits
					__UpperCAmelCase    :     str													=	(1, 10_00)
					self.assertEqual(outputs.logits.shape       ,       a_ )

					__UpperCAmelCase    :     Dict													=	jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] )

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










from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


__A   			=logging.get_logger(__name__)


if is_vision_available():
				import PIL

class 		UpperCAmelCase__			(			__UpperCamelCase   ):




			'''simple docstring'''






			UpperCamelCase									=       ["""pixel_values"""]




			def __init__(   self							: Tuple       ,       a_							: bool = True       ,       a_							: Dict[str, int] = None       ,       a_							: PILImageResampling = PILImageResampling.BICUBIC       ,       a_							: bool = True       ,       a_							: Dict[str, int] = None       ,       a_							: bool = True       ,       a_							: Union[int, float] = 1 / 2_55       ,       a_							: bool = True       ,       a_							: Optional[Union[float, List[float]]] = None       ,       a_							: Optional[Union[float, List[float]]] = None       ,       a_							: bool = True       ,       **a_							: str       ,       ):
					'''simple docstring'''





					super().__init__(**a_ )
					__UpperCAmelCase    :     List[Any]													=	size if size is not None else {'''shortest_edge''': 2_24}
					__UpperCAmelCase    :     List[str]													=	get_size_dict(a_       ,       default_to_square=a_ )
					__UpperCAmelCase    :     int													=	crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
					__UpperCAmelCase    :     Optional[int]													=	get_size_dict(a_       ,       default_to_square=a_       ,       param_name='''crop_size''' )

					__UpperCAmelCase    :     int													=	do_resize
					__UpperCAmelCase    :     Union[str, Any]													=	size
					__UpperCAmelCase    :     Union[str, Any]													=	resample
					__UpperCAmelCase    :     Any													=	do_center_crop
					__UpperCAmelCase    :     Any													=	crop_size
					__UpperCAmelCase    :     Any													=	do_rescale
					__UpperCAmelCase    :     Dict													=	rescale_factor
					__UpperCAmelCase    :     Union[str, Any]													=	do_normalize
					__UpperCAmelCase    :     Any													=	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
					__UpperCAmelCase    :     int													=	image_std if image_std is not None else OPENAI_CLIP_STD
					__UpperCAmelCase    :     List[str]													=	do_convert_rgb




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: np.ndarray       ,       a_							: Dict[str, int]       ,       a_							: PILImageResampling = PILImageResampling.BICUBIC       ,       a_							: Optional[Union[str, ChannelDimension]] = None       ,       **a_							: Optional[int]       ,       ):
					'''simple docstring'''





					__UpperCAmelCase    :     Dict													=	get_size_dict(a_       ,       default_to_square=a_ )
					if "shortest_edge" not in size:
							raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' )
					__UpperCAmelCase    :     Optional[int]													=	get_resize_output_image_size(a_       ,       size=size['''shortest_edge''']       ,       default_to_square=a_ )
					return resize(a_       ,       size=a_       ,       resample=a_       ,       data_format=a_       ,       **a_ )




			def  snake_case__     (   self							: Union[str, Any]       ,       a_							: np.ndarray       ,       a_							: Dict[str, int]       ,       a_							: Optional[Union[str, ChannelDimension]] = None       ,       **a_							: Dict       ,       ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[Any]													=	get_size_dict(a_ )
					if "height" not in size or "width" not in size:
							raise ValueError(F'The `size` parameter must contain the keys (height, width). Got {size.keys()}' )
					return center_crop(a_       ,       size=(size['''height'''], size['''width'''])       ,       data_format=a_       ,       **a_ )




			def  snake_case__     (   self							: Union[str, Any]       ,       a_							: np.ndarray       ,       a_							: Union[int, float]       ,       a_							: Optional[Union[str, ChannelDimension]] = None       ,       **a_							: List[str]       ,       ):
					'''simple docstring'''





					return rescale(a_       ,       scale=a_       ,       data_format=a_       ,       **a_ )




			def  snake_case__     (   self							: Optional[Any]       ,       a_							: np.ndarray       ,       a_							: Union[float, List[float]]       ,       a_							: Union[float, List[float]]       ,       a_							: Optional[Union[str, ChannelDimension]] = None       ,       **a_							: Dict       ,       ):
					'''simple docstring'''





					return normalize(a_       ,       mean=a_       ,       std=a_       ,       data_format=a_       ,       **a_ )




			def  snake_case__     (   self							: Any       ,       a_							: ImageInput       ,       a_							: bool = None       ,       a_							: Dict[str, int] = None       ,       a_							: PILImageResampling = None       ,       a_							: bool = None       ,       a_							: int = None       ,       a_							: bool = None       ,       a_							: float = None       ,       a_							: bool = None       ,       a_							: Optional[Union[float, List[float]]] = None       ,       a_							: Optional[Union[float, List[float]]] = None       ,       a_							: bool = None       ,       a_							: Optional[Union[str, TensorType]] = None       ,       a_							: Optional[ChannelDimension] = ChannelDimension.FIRST       ,       **a_							: Dict       ,       ):
					'''simple docstring'''





					__UpperCAmelCase    :     Tuple													=	do_resize if do_resize is not None else self.do_resize
					__UpperCAmelCase    :     Optional[Any]													=	size if size is not None else self.size
					__UpperCAmelCase    :     Dict													=	get_size_dict(a_       ,       param_name='''size'''       ,       default_to_square=a_ )
					__UpperCAmelCase    :     int													=	resample if resample is not None else self.resample
					__UpperCAmelCase    :     Optional[Any]													=	do_center_crop if do_center_crop is not None else self.do_center_crop
					__UpperCAmelCase    :     Any													=	crop_size if crop_size is not None else self.crop_size
					__UpperCAmelCase    :     Dict													=	get_size_dict(a_       ,       param_name='''crop_size'''       ,       default_to_square=a_ )
					__UpperCAmelCase    :     int													=	do_rescale if do_rescale is not None else self.do_rescale
					__UpperCAmelCase    :     Optional[int]													=	rescale_factor if rescale_factor is not None else self.rescale_factor
					__UpperCAmelCase    :     List[str]													=	do_normalize if do_normalize is not None else self.do_normalize
					__UpperCAmelCase    :     Optional[int]													=	image_mean if image_mean is not None else self.image_mean
					__UpperCAmelCase    :     Tuple													=	image_std if image_std is not None else self.image_std
					__UpperCAmelCase    :     List[str]													=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

					__UpperCAmelCase    :     List[str]													=	make_list_of_images(a_ )

					if not valid_images(a_ ):
							raise ValueError(
							    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
							    '''torch.Tensor, tf.Tensor or jax.ndarray.''' )

					if do_resize and size is None:
							raise ValueError('''Size must be specified if do_resize is True.''' )

					if do_center_crop and crop_size is None:
							raise ValueError('''Crop size must be specified if do_center_crop is True.''' )

					if do_rescale and rescale_factor is None:
							raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )

					if do_normalize and (image_mean is None or image_std is None):
							raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )

					# PIL RGBA images are converted to RGB
					if do_convert_rgb:
							__UpperCAmelCase    :     Optional[Any]													=	[convert_to_rgb(a_ ) for image in images]

					# All transformations expect numpy arrays.
					__UpperCAmelCase    :     int													=	[to_numpy_array(a_ ) for image in images]

					if do_resize:
							__UpperCAmelCase    :     int													=	[self.resize(image=a_       ,       size=a_       ,       resample=a_ ) for image in images]

					if do_center_crop:
							__UpperCAmelCase    :     List[str]													=	[self.center_crop(image=a_       ,       size=a_ ) for image in images]

					if do_rescale:
							__UpperCAmelCase    :     Dict													=	[self.rescale(image=a_       ,       scale=a_ ) for image in images]

					if do_normalize:
							__UpperCAmelCase    :     Optional[int]													=	[self.normalize(image=a_       ,       mean=a_       ,       std=a_ ) for image in images]

					__UpperCAmelCase    :     Optional[int]													=	[to_channel_dimension_format(a_       ,       a_ ) for image in images]

					__UpperCAmelCase    :     Union[str, Any]													=	{'''pixel_values''': images}
					return BatchFeature(data=a_       ,       tensor_type=a_ )





