



'''simple docstring'''


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							,  lowerCAmelCase_							,  lowerCAmelCase_=3							,  lowerCAmelCase_=3_2							,  lowerCAmelCase_=3							,  lowerCAmelCase_=1_0							,  lowerCAmelCase_=[1_0, 2_0, 3_0, 4_0]							,  lowerCAmelCase_=[1, 1, 2, 1]							,  lowerCAmelCase_=True							,  lowerCAmelCase_=True							,  lowerCAmelCase_="relu"							,  lowerCAmelCase_=3							,  lowerCAmelCase_=None							,  ) ->      Optional[int]:



						"""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(_A)




	def       lowercase_  (   self) ->      Any:



						"""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       lowercase_  (   self) ->      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       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_) ->      Union[str, Any]:



						"""simple docstring"""







						a_       		=FlaxRegNetModel(config=_A)
						a_       		=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 // 3_2, self.image_size // 3_2)							,  )




	def       lowercase_  (   self							,  lowerCAmelCase_							,  lowerCAmelCase_) ->      Any:



						"""simple docstring"""







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




	def       lowercase_  (   self) ->      List[str]:



						"""simple docstring"""







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







@require_flax
class 	UpperCAmelCase	(		snake_case__					,	unittest.TestCase):


	'''simple docstring'''




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

	__magic_name__					: List[str]  =      False
	__magic_name__					: Optional[int]  =      False
	__magic_name__					: List[str]  =      False




	def       lowercase_  (   self) ->      Optional[Any]:



						"""simple docstring"""







						a_       		=FlaxRegNetModelTester(self)
						a_       		=ConfigTester(self							,  config_class=_A							,  has_text_modality=_A)




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



						"""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       lowercase_  (   self) ->      Union[str, Any]:



						"""simple docstring"""







						return




	def       lowercase_  (   self) ->      int:



						"""simple docstring"""







						a_       		=self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_A)




	def       lowercase_  (   self) ->      List[str]:



						"""simple docstring"""







						a_       		=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       lowercase_  (   self) ->      List[Any]:



						"""simple docstring"""







						pass




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



						"""simple docstring"""







						pass




	def       lowercase_  (   self) ->      Dict:



						"""simple docstring"""







						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											a_       		=model_class(_A)
											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]							,  _A)




	def       lowercase_  (   self) ->      Dict:



						"""simple docstring"""







						def check_hidden_states_output(lowerCAmelCase_							,  lowerCAmelCase_							,  lowerCAmelCase_):
											a_       		=model_class(_A)

											a_       		=model(**self._prepare_for_class(_A							,  _A))

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

											a_       		=self.model_tester.num_stages
											self.assertEqual(len(_A)							,  expected_num_stages + 1)

						a_       		=self.model_tester.prepare_config_and_inputs_for_common()

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

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

											check_hidden_states_output(_A							,  _A							,  _A)




	def       lowercase_  (   self) ->      List[str]:



						"""simple docstring"""







						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(_A							,  _A)
																a_       		=model_class(_A)

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

																with self.subTest("JIT Enabled"):
																					a_       		=model_jitted(**_A).to_tuple()

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


					'''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       lowercase_  (   self) ->      Optional[int]:



						"""simple docstring"""







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




	@slow
	def       lowercase_  (   self) ->      List[Any]:



						"""simple docstring"""







						a_       		=FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040")

						a_       		=self.default_image_processor
						a_       		=prepare_img()
						a_       		=image_processor(images=_A							,  return_tensors="np")

						a_       		=model(**_A)

						# verify the logits
						a_       		=(1, 1_0_0_0)
						self.assertEqual(outputs.logits.shape							,  _A)

						a_       		=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))







'''simple docstring'''


import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

lowercase							       =			logging.getLogger()






def  UpperCAmelCase_       (		lowercase__       ):


     '''simple docstring'''







     a_       		={}
     a_       		=os.path.join(lowercase__       ,	"all_results.json"       )
     if os.path.exists(lowercase__       ):
          with open(lowercase__       ,	"r"       ) as f:
               a_       		=json.load(lowercase__       )
     else:
          raise ValueError(F"""can't find {path}"""       )
     return results


lowercase							       =			logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







@require_torch_tpu
class 	UpperCAmelCase	(		__a):


 '''simple docstring'''




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



      """simple docstring"""







      import xla_spawn

      a_       		=self.get_auto_remove_tmp_dir()
      a_       		=f"""
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            """.split()

      with patch.object(lowerCAmelCase_							,  "argv"							,  lowerCAmelCase_):
           a_       		=time()
           xla_spawn.main()
           a_       		=time()

           a_       		=get_results(lowerCAmelCase_)
           self.assertGreaterEqual(result["eval_accuracy"]							,  0.7_5)

           # Assert that the script takes less than 500 seconds to make sure it doesn't hang.
           self.assertLess(end - start							,  5_0_0)




 def       lowercase_  (   self) ->      Tuple:



      """simple docstring"""







      import xla_spawn

      a_       		="\n            ./tests/test_trainer_tpu.py\n            --num_cores=8\n            ./tests/test_trainer_tpu.py\n            ".split()
      with patch.object(lowerCAmelCase_							,  "argv"							,  lowerCAmelCase_):
           xla_spawn.main()


