



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




         """simple docstring"""

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


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




         """simple docstring"""

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

         lowercase__  =	self.get_config()

         return config, pixel_values


   def       UpperCAmelCase		(    self	:      Any)						->					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      ,					image_size=self.image_size      ,					)


   def       UpperCAmelCase		(    self	:      Any      ,					lowerCAmelCase	:      Optional[Any]      ,					lowerCAmelCase	:      Optional[int])						->					Optional[int]:




         """simple docstring"""

         lowercase__  =	FlaxRegNetModel(config=lowerCAmelCase)
         lowercase__  =	model(lowerCAmelCase)

         # 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       UpperCAmelCase		(    self	:      Tuple      ,					lowerCAmelCase	:      List[Any]      ,					lowerCAmelCase	:      Tuple)						->					Optional[int]:




         """simple docstring"""

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



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




         """simple docstring"""

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



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

   '''simple docstring'''




   A     :	Union[str, Any]												=     (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

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


   def       UpperCAmelCase		(    self	:      Optional[Any])						->					None:




         """simple docstring"""

         lowercase__  =	FlaxRegNetModelTester(self)
         lowercase__  =	ConfigTester(self      ,					config_class=lowerCAmelCase      ,					has_text_modality=lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      List[Any])						->					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       UpperCAmelCase		(    self	:      List[str])						->					Dict:




         """simple docstring"""

         return


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




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCAmelCase)


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




         """simple docstring"""

         lowercase__  =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase)


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




         """simple docstring"""

         pass


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




         """simple docstring"""

         pass


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




         """simple docstring"""

         lowercase__,						lowercase__  =	self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase__  =	['pixel_values']
               self.assertListEqual(arg_names[:1]      ,					lowerCAmelCase)


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




         """simple docstring"""

         def check_hidden_states_output(lowerCAmelCase	:      Optional[Any]      ,					lowerCAmelCase	:      Optional[int]      ,					lowerCAmelCase	:      Optional[int]):
               lowercase__  =	model_class(lowerCAmelCase)

               lowercase__  =	model(**self._prepare_for_class(lowerCAmelCase      ,					lowerCAmelCase))

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

               lowercase__  =	self.model_tester.num_stages
               self.assertEqual(len(lowerCAmelCase)      ,					expected_num_stages + 1)

         lowercase__,						lowercase__  =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               lowercase__  =	True
               check_hidden_states_output(lowerCAmelCase      ,					lowerCAmelCase      ,					lowerCAmelCase)

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

               check_hidden_states_output(lowerCAmelCase      ,					lowerCAmelCase      ,					lowerCAmelCase)



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




         """simple docstring"""

         lowercase__,						lowercase__  =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__):
                     lowercase__  =	self._prepare_for_class(lowerCAmelCase      ,					lowerCAmelCase)
                     lowercase__  =	model_class(lowerCAmelCase)

                     @jax.jit
                     def model_jitted(lowerCAmelCase	:      Union[str, Any]      ,					**lowerCAmelCase	:      str):
                           return model(pixel_values=lowerCAmelCase      ,					**lowerCAmelCase)

                     with self.subTest('JIT Enabled'):
                           lowercase__  =	model_jitted(**lowerCAmelCase).to_tuple()

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

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

def 	_lowerCAmelCase (    ):
      lowercase__  =	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
      return image



@require_flax
class    UpperCAmelCase__(				unittest.TestCase						):

   '''simple docstring'''




   @cached_property
   def       UpperCAmelCase		(    self	:      Dict)						->					Union[str, Any]:




         """simple docstring"""

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



   @slow
   def       UpperCAmelCase		(    self	:      List[Any])						->					Optional[int]:




         """simple docstring"""

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

         lowercase__  =	self.default_image_processor
         lowercase__  =	prepare_img()
         lowercase__  =	image_processor(images=lowerCAmelCase      ,					return_tensors='np')

         lowercase__  =	model(**lowerCAmelCase)

         # verify the logits
         lowercase__  =	(1, 10_00)
         self.assertEqual(outputs.logits.shape      ,					lowerCAmelCase)

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

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





from argparse import ArgumentParser

from .add_new_model import AddNewModelCommand
from .add_new_model_like import AddNewModelLikeCommand
from .convert import ConvertCommand
from .download import DownloadCommand
from .env import EnvironmentCommand
from .lfs import LfsCommands
from .pt_to_tf import PTtoTFCommand
from .run import RunCommand
from .serving import ServeCommand
from .user import UserCommands

def 	_lowerCAmelCase (    ):
      lowercase__  =	ArgumentParser('Transformers CLI tool'    ,	usage='transformers-cli <command> [<args>]'						)
      lowercase__  =	parser.add_subparsers(help='transformers-cli command helpers'						)

      # Register commands
      ConvertCommand.register_subcommand(A__						)
      DownloadCommand.register_subcommand(A__						)
      EnvironmentCommand.register_subcommand(A__						)
      RunCommand.register_subcommand(A__						)
      ServeCommand.register_subcommand(A__						)
      UserCommands.register_subcommand(A__						)
      AddNewModelCommand.register_subcommand(A__						)
      AddNewModelLikeCommand.register_subcommand(A__						)
      LfsCommands.register_subcommand(A__						)
      PTtoTFCommand.register_subcommand(A__						)

      # Let's go
      lowercase__  =	parser.parse_args()

      if not hasattr(A__    ,	'func'						):
            parser.print_help()
            exit(1						)

      # Run
      lowercase__  =	args.func(A__						)
      service.run()


if __name__ == "__main__":
       main()
