






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   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		def __init__(							self				,		_UpperCamelCase				,		_UpperCamelCase=3				,		_UpperCamelCase=3_2				,		_UpperCamelCase=3				,		_UpperCamelCase=1_0				,		_UpperCamelCase=[1_0, 2_0, 3_0, 4_0]				,		_UpperCamelCase=[1, 1, 2, 1]				,		_UpperCamelCase=True				,		_UpperCamelCase=True				,		_UpperCamelCase="relu"				,		_UpperCamelCase=3				,		_UpperCamelCase=None				,		)	->							Union[str, Any]:
							UpperCAmelCase_    :      Any            =						parent
							UpperCAmelCase_    :      List[str]            =						batch_size
							UpperCAmelCase_    :      Optional[int]            =						image_size
							UpperCAmelCase_    :      Union[str, Any]            =						num_channels
							UpperCAmelCase_    :      int            =						embeddings_size
							UpperCAmelCase_    :      Optional[int]            =						hidden_sizes
							UpperCAmelCase_    :      Optional[int]            =						depths
							UpperCAmelCase_    :      Optional[Any]            =						is_training
							UpperCAmelCase_    :      Tuple            =						use_labels
							UpperCAmelCase_    :      List[str]            =						hidden_act
							UpperCAmelCase_    :      List[Any]            =						num_labels
							UpperCAmelCase_    :      Optional[Any]            =						scope
							UpperCAmelCase_    :      Any            =						len(_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							UpperCAmelCase_    :      Union[str, Any]            =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							UpperCAmelCase_    :      str            =						self.get_config()

							return config, pixel_values



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							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 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Dict:
							UpperCAmelCase_    :      Any            =						FlaxRegNetModel(config=_UpperCamelCase   )
							UpperCAmelCase_    :      Union[str, Any]            =						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 // 3_2, self.image_size // 3_2)				,		)



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase   )	->							List[Any]:
							UpperCAmelCase_    :      Union[str, Any]            =						self.num_labels
							UpperCAmelCase_    :      List[Any]            =						FlaxRegNetForImageClassification(config=_UpperCamelCase   )
							UpperCAmelCase_    :      Union[str, Any]            =						model(_UpperCamelCase   )
							self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.num_labels)   )



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_    :      str            =						self.prepare_config_and_inputs()
							UpperCAmelCase_       ,  UpperCAmelCase_    :      Any            =						config_and_inputs
							UpperCAmelCase_    :      Optional[Any]            =						{'pixel_values': pixel_values}
							return config, inputs_dict





@require_flax
class   lowerCamelCase      (_snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    List[str]       						=  (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

		_snake_case    :    int       						=  False
		_snake_case    :    Optional[Any]       						=  False
		_snake_case    :    Optional[int]       						=  False



		def 					__UpperCAmelCase			(							self   )	->							None:
							UpperCAmelCase_    :      List[Any]            =						FlaxRegNetModelTester(self   )
							UpperCAmelCase_    :      Dict            =						ConfigTester(self				,		config_class=_UpperCamelCase				,		has_text_modality=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							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 					__UpperCAmelCase			(							self   )	->							str:
							return



		def 					__UpperCAmelCase			(							self   )	->							Any:
							UpperCAmelCase_    :      Union[str, Any]            =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							UpperCAmelCase_    :      str            =						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 					__UpperCAmelCase			(							self   )	->							str:
							pass



		@unittest.skip(reason='RegNet does not support input and output embeddings'   )
		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							pass



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      Tuple            =						self.model_tester.prepare_config_and_inputs_for_common()

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

												UpperCAmelCase_    :      List[str]            =						['pixel_values']
												self.assertListEqual(arg_names[:1]				,		_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							str:
							def check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      Optional[Any]            =						model_class(_UpperCamelCase   )

												UpperCAmelCase_    :      str            =						model(**self._prepare_for_class(_UpperCamelCase				,		_UpperCamelCase   )   )

												UpperCAmelCase_    :      Optional[int]            =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												UpperCAmelCase_    :      Tuple            =						self.model_tester.num_stages
												self.assertEqual(len(_UpperCamelCase   )				,		expected_num_stages + 1   )

							UpperCAmelCase_       ,  UpperCAmelCase_    :      Optional[int]            =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												UpperCAmelCase_    :      Tuple            =						True
												check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )

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

												check_hidden_states_output(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      str            =						self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												with self.subTest(model_class.__name__   ):
																	UpperCAmelCase_    :      Dict            =						self._prepare_for_class(_UpperCamelCase				,		_UpperCamelCase   )
																	UpperCAmelCase_    :      Dict            =						model_class(_UpperCamelCase   )

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

																	with self.subTest('JIT Enabled'   ):
																						UpperCAmelCase_    :      Optional[int]            =						model_jitted(**_UpperCamelCase   ).to_tuple()

																	with self.subTest('JIT Disabled'   ):
																						with jax.disable_jit():
																											UpperCAmelCase_    :      int            =						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      lowercase__      (     ):


					'''simple docstring'''


					UpperCAmelCase_    :      List[str]            =						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
					return image






@require_flax
class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		@cached_property
		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'   ) if is_vision_available() else None



		@slow
		def 					__UpperCAmelCase			(							self   )	->							int:
							UpperCAmelCase_    :      Tuple            =						FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'   )

							UpperCAmelCase_    :      Tuple            =						self.default_image_processor
							UpperCAmelCase_    :      List[Any]            =						prepare_img()
							UpperCAmelCase_    :      Any            =						image_processor(images=_UpperCamelCase				,		return_tensors='np'   )

							UpperCAmelCase_    :      int            =						model(**_UpperCamelCase   )

							# verify the logits
							UpperCAmelCase_    :      Union[str, Any]            =						(1, 1_0_0_0)
							self.assertEqual(outputs.logits.shape				,		_UpperCamelCase   )

							UpperCAmelCase_    :      Tuple            =						jnp.array([-0.41_80, -1.50_51, -3.48_36]   )

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














__UpperCAmelCase								=						{
    'Pillow': 'Pillow<10.0.0',
    'accelerate': 'accelerate>=0.20.3',
    'av': 'av==9.2.0',
    'beautifulsoup4': 'beautifulsoup4',
    'black': 'black~=23.1',
    'codecarbon': 'codecarbon==1.2.0',
    'cookiecutter': 'cookiecutter==1.7.3',
    'dataclasses': 'dataclasses',
    'datasets': 'datasets!=2.5.0',
    'decord': 'decord==0.6.0',
    'deepspeed': 'deepspeed>=0.9.3',
    'diffusers': 'diffusers',
    'dill': 'dill<0.3.5',
    'evaluate': 'evaluate>=0.2.0',
    'fairscale': 'fairscale>0.3',
    'faiss-cpu': 'faiss-cpu',
    'fastapi': 'fastapi',
    'filelock': 'filelock',
    'flax': 'flax>=0.4.1,<=0.7.0',
    'ftfy': 'ftfy',
    'fugashi': 'fugashi>=1.0',
    'GitPython': 'GitPython<3.1.19',
    'hf-doc-builder': 'hf-doc-builder>=0.3.0',
    'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0',
    'importlib_metadata': 'importlib_metadata',
    'ipadic': 'ipadic>=1.0.0,<2.0',
    'isort': 'isort>=5.5.4',
    'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13',
    'jaxlib': 'jaxlib>=0.1.65,<=0.4.13',
    'jieba': 'jieba',
    'kenlm': 'kenlm',
    'keras-nlp': 'keras-nlp>=0.3.1',
    'librosa': 'librosa',
    'nltk': 'nltk',
    'natten': 'natten>=0.14.6',
    'numpy': 'numpy>=1.17',
    'onnxconverter-common': 'onnxconverter-common',
    'onnxruntime-tools': 'onnxruntime-tools>=1.4.2',
    'onnxruntime': 'onnxruntime>=1.4.0',
    'opencv-python': 'opencv-python',
    'optuna': 'optuna',
    'optax': 'optax>=0.0.8,<=0.1.4',
    'packaging': 'packaging>=20.0',
    'parameterized': 'parameterized',
    'phonemizer': 'phonemizer',
    'protobuf': 'protobuf',
    'psutil': 'psutil',
    'pyyaml': 'pyyaml>=5.1',
    'pydantic': 'pydantic<2',
    'pytest': 'pytest>=7.2.0',
    'pytest-timeout': 'pytest-timeout',
    'pytest-xdist': 'pytest-xdist',
    'python': 'python>=3.8.0',
    'ray[tune]': 'ray[tune]',
    'regex': 'regex!=2019.12.17',
    'requests': 'requests',
    'rhoknp': 'rhoknp>=1.1.0,<1.3.1',
    'rjieba': 'rjieba',
    'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1',
    'ruff': 'ruff>=0.0.241,<=0.0.259',
    'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0',
    'sacremoses': 'sacremoses',
    'safetensors': 'safetensors>=0.3.1',
    'sagemaker': 'sagemaker>=2.31.0',
    'scikit-learn': 'scikit-learn',
    'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
    'sigopt': 'sigopt',
    'starlette': 'starlette',
    'sudachipy': 'sudachipy>=0.6.6',
    'sudachidict_core': 'sudachidict_core>=20220729',
    'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14',
    'tensorflow': 'tensorflow>=2.6,<2.14',
    'tensorflow-text': 'tensorflow-text<2.14',
    'tf2onnx': 'tf2onnx',
    'timeout-decorator': 'timeout-decorator',
    'timm': 'timm',
    'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14',
    'torch': 'torch>=1.9,!=1.12.0',
    'torchaudio': 'torchaudio',
    'torchvision': 'torchvision',
    'pyctcdecode': 'pyctcdecode>=0.4.0',
    'tqdm': 'tqdm>=4.27',
    'unidic': 'unidic>=1.0.2',
    'unidic_lite': 'unidic_lite>=1.0.7',
    'urllib3': 'urllib3<2.0.0',
    'uvicorn': 'uvicorn',
}






