




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   :			List[Any]      ,				UpperCAmelCase__   :			Optional[int]      ,				UpperCAmelCase__   :			List[str]=3      ,				UpperCAmelCase__   :			Optional[int]=32      ,				UpperCAmelCase__   :			Tuple=3      ,				UpperCAmelCase__   :			Union[str, Any]=10      ,				UpperCAmelCase__   :			int=[10, 20, 30, 40]      ,				UpperCAmelCase__   :			Optional[int]=[1, 1, 2, 1]      ,				UpperCAmelCase__   :			Any=True      ,				UpperCAmelCase__   :			str=True      ,				UpperCAmelCase__   :			Union[str, Any]="relu"      ,				UpperCAmelCase__   :			Tuple=3      ,				UpperCAmelCase__   :			Any=None      ,				)		->Optional[Any]:





           '''simple docstring'''

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


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





           '''simple docstring'''

           A__   				=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           A__   				=					self.get_config()

           return config, pixel_values


    def  SCREAMING_SNAKE_CASE							(    self   :			int)		->int:





           '''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  SCREAMING_SNAKE_CASE							(    self   :			str      ,				UpperCAmelCase__   :			str      ,				UpperCAmelCase__   :			str)		->List[Any]:





           '''simple docstring'''

           A__   				=					FlaxRegNetModel(config=UpperCAmelCase__)
           A__   				=					model(UpperCAmelCase__)

           # 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  SCREAMING_SNAKE_CASE							(    self   :			int      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			Optional[int])		->Dict:





           '''simple docstring'''

           A__   				=					self.num_labels
           A__   				=					FlaxRegNetForImageClassification(config=UpperCAmelCase__)
           A__   				=					model(UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.num_labels))





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





           '''simple docstring'''

           A__   				=					self.prepare_config_and_inputs()
           A__				,							A__   				=					config_and_inputs
           A__   				=					{'''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  SCREAMING_SNAKE_CASE							(    self   :			Any)		->None:





           '''simple docstring'''

           A__   				=					FlaxRegNetModelTester(self)
           A__   				=					ConfigTester(self      ,				config_class=UpperCAmelCase__      ,				has_text_modality=UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[Any])		->Tuple:





           '''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  SCREAMING_SNAKE_CASE							(    self   :			List[Any])		->Dict:





           '''simple docstring'''

           return


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





           '''simple docstring'''

           A__   				=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase__)


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





           '''simple docstring'''

           A__   				=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__)


    @unittest.skip(reason='''RegNet does not use inputs_embeds''')
    def  SCREAMING_SNAKE_CASE							(    self   :			List[str])		->List[Any]:





           '''simple docstring'''

           pass


    @unittest.skip(reason='''RegNet does not support input and output embeddings''')
    def  SCREAMING_SNAKE_CASE							(    self   :			List[str])		->str:





           '''simple docstring'''

           pass


    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->Any:





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

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

                  A__   				=					['''pixel_values''']
                  self.assertListEqual(arg_names[:1]      ,				UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			Tuple)		->Optional[Any]:





           '''simple docstring'''

           def check_hidden_states_output(UpperCAmelCase__   :			Optional[Any]      ,				UpperCAmelCase__   :			Union[str, Any]      ,				UpperCAmelCase__   :			Tuple):
                  A__   				=					model_class(UpperCAmelCase__)

                  A__   				=					model(**self._prepare_for_class(UpperCAmelCase__      ,				UpperCAmelCase__))

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

                  A__   				=					self.model_tester.num_stages
                  self.assertEqual(len(UpperCAmelCase__)      ,				expected_num_stages + 1)

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A__   				=					True
                  check_hidden_states_output(UpperCAmelCase__      ,				UpperCAmelCase__      ,				UpperCAmelCase__)

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

                  check_hidden_states_output(UpperCAmelCase__      ,				UpperCAmelCase__      ,				UpperCAmelCase__)





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





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  with self.subTest(model_class.__name__):
                         A__   				=					self._prepare_for_class(UpperCAmelCase__      ,				UpperCAmelCase__)
                         A__   				=					model_class(UpperCAmelCase__)

                         @jax.jit
                         def model_jitted(UpperCAmelCase__   :			List[Any]      ,				**UpperCAmelCase__   :			Optional[Any]):
                                return model(pixel_values=UpperCAmelCase__      ,				**UpperCAmelCase__)

                         with self.subTest('''JIT Enabled'''):
                                A__   				=					model_jitted(**UpperCAmelCase__).to_tuple()

                         with self.subTest('''JIT Disabled'''):
                                with jax.disable_jit():
                                       A__   				=					model_jitted(**UpperCAmelCase__).to_tuple()

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







def SCREAMING_SNAKE_CASE       ( )     -> Dict:



       """simple docstring"""

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


@require_flax
class        UpperCamelCase_					(				unittest.TestCase  ):

    '''simple docstring'''






    @cached_property
    def  SCREAMING_SNAKE_CASE							(    self   :			List[str])		->Optional[Any]:





           '''simple docstring'''

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





    @slow
    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->str:





           '''simple docstring'''

           A__   				=					FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''')

           A__   				=					self.default_image_processor
           A__   				=					prepare_img()
           A__   				=					image_processor(images=UpperCAmelCase__      ,				return_tensors='''np''')

           A__   				=					model(**UpperCAmelCase__)

           # verify the logits
           A__   				=					(1, 1_000)
           self.assertEqual(outputs.logits.shape      ,				UpperCAmelCase__)

           A__   				=					jnp.array([-0.4180, -1.5051, -3.4836])

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








from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase			:	str							 =     logging.get_logger(__name__)


class        UpperCamelCase_					(				UpperCAmelCase__  ):

    '''simple docstring'''






    UpperCAmelCase__													=   ['''pixel_values''']


    def __init__(    self   :			List[Any]      ,				UpperCAmelCase__   :			bool = True      ,				UpperCAmelCase__   :			int = 32      ,				UpperCAmelCase__   :			Dict=PILImageResampling.BILINEAR      ,				UpperCAmelCase__   :			bool = True      ,				**UpperCAmelCase__   :			Optional[int]      ,				)		->None:





           '''simple docstring'''

           A__   				=					do_resize
           A__   				=					do_rescale
           A__   				=					size_divisor
           A__   				=					resample
           super().__init__(**UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			int      ,				UpperCAmelCase__   :			np.ndarray      ,				UpperCAmelCase__   :			int      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			Optional[ChannelDimension] = None      ,				**UpperCAmelCase__   :			Dict)		->np.ndarray:





           '''simple docstring'''

           A__				,							A__   				=					get_image_size(UpperCAmelCase__)
           # Rounds the height and width down to the closest multiple of size_divisor
           A__   				=					height // size_divisor * size_divisor
           A__   				=					width // size_divisor * size_divisor
           A__   				=					resize(UpperCAmelCase__      ,				(new_h, new_w)      ,				resample=UpperCAmelCase__      ,				data_format=UpperCAmelCase__      ,				**UpperCAmelCase__)
           return image


    def  SCREAMING_SNAKE_CASE							(    self   :			List[Any]      ,				UpperCAmelCase__   :			np.ndarray      ,				UpperCAmelCase__   :			float      ,				UpperCAmelCase__   :			Optional[ChannelDimension] = None      ,				**UpperCAmelCase__   :			List[str])		->np.ndarray:





           '''simple docstring'''

           return rescale(image=UpperCAmelCase__      ,				scale=UpperCAmelCase__      ,				data_format=UpperCAmelCase__      ,				**UpperCAmelCase__)





    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int]      ,				UpperCAmelCase__   :			Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]]      ,				UpperCAmelCase__   :			Optional[bool] = None      ,				UpperCAmelCase__   :			Optional[int] = None      ,				UpperCAmelCase__   :			Dict=None      ,				UpperCAmelCase__   :			Optional[bool] = None      ,				UpperCAmelCase__   :			Optional[Union[TensorType, str]] = None      ,				UpperCAmelCase__   :			ChannelDimension = ChannelDimension.FIRST      ,				**UpperCAmelCase__   :			List[str]      ,				)		->BatchFeature:





           '''simple docstring'''

           A__   				=					do_resize if do_resize is not None else self.do_resize
           A__   				=					do_rescale if do_rescale is not None else self.do_rescale
           A__   				=					size_divisor if size_divisor is not None else self.size_divisor
           A__   				=					resample if resample is not None else self.resample

           if do_resize and size_divisor is None:
                  raise ValueError('''size_divisor is required for resizing''')

           A__   				=					make_list_of_images(UpperCAmelCase__)

           if not valid_images(UpperCAmelCase__):
                  raise ValueError('''Invalid image(s)''')

           # All transformations expect numpy arrays.
           A__   				=					[to_numpy_array(UpperCAmelCase__) for img in images]

           if do_resize:
                  A__   				=					[self.resize(UpperCAmelCase__      ,				size_divisor=UpperCAmelCase__      ,				resample=UpperCAmelCase__) for image in images]

           if do_rescale:
                  A__   				=					[self.rescale(UpperCAmelCase__      ,				scale=1 / 255) for image in images]

           A__   				=					[to_channel_dimension_format(UpperCAmelCase__      ,				UpperCAmelCase__) for image in images]

           A__   				=					{'''pixel_values''': images}
           return BatchFeature(data=UpperCAmelCase__      ,				tensor_type=UpperCAmelCase__)


