


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






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




             _lowerCamelCase       :		Any		=parent
             _lowerCamelCase       :		Optional[Any]		=batch_size
             _lowerCamelCase       :		Optional[int]		=image_size
             _lowerCamelCase       :		str		=num_channels
             _lowerCamelCase       :		List[Any]		=embeddings_size
             _lowerCamelCase       :		Any		=hidden_sizes
             _lowerCamelCase       :		List[Any]		=depths
             _lowerCamelCase       :		List[Any]		=is_training
             _lowerCamelCase       :		List[Any]		=use_labels
             _lowerCamelCase       :		Dict		=hidden_act
             _lowerCamelCase       :		List[Any]		=num_labels
             _lowerCamelCase       :		int		=scope
             _lowerCamelCase       :		List[str]		=len(lowercase_ )






      def        lowerCamelCase       (					self						:     List[Any] )					->						Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

             return config, pixel_values






      def        lowerCamelCase       (					self						:     Optional[Any] )					->						List[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        lowerCamelCase       (					self						:     Union[str, Any]			,   lowercase_						:     Dict			,   lowercase_						:     int )					->						List[Any]:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=FlaxRegNetModel(config=lowercase_ )
             _lowerCamelCase       :		Any		=model(lowercase_ )

             # 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        lowerCamelCase       (					self						:     Any			,   lowercase_						:     Optional[Any]			,   lowercase_						:     int )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		Any		=self.num_labels
             _lowerCamelCase       :		List[Any]		=FlaxRegNetForImageClassification(config=lowercase_ )
             _lowerCamelCase       :		Optional[int]		=model(lowercase_ )
             self.parent.assertEqual(result.logits.shape			,   (self.batch_size, self.num_labels) )






      def        lowerCamelCase       (					self						:     Union[str, Any] )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=self.prepare_config_and_inputs()
             _lowerCamelCase	,     _lowerCamelCase       :		List[str]		=config_and_inputs
             _lowerCamelCase       :		int		={'pixel_values': pixel_values}
             return config, inputs_dict




@require_flax
class A  (   UpperCamelCase_    ,							unittest.TestCase     ):
      UpperCamelCase__							:  List[Any]      =(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

      UpperCamelCase__							:  int      =False
      UpperCamelCase__							:  List[str]      =False
      UpperCamelCase__							:  Optional[Any]      =False






      def        lowerCamelCase       (					self						:     Optional[int] )					->						None:
             """simple docstring"""




             _lowerCamelCase       :		str		=FlaxRegNetModelTester(self )
             _lowerCamelCase       :		List[str]		=ConfigTester(self			,   config_class=lowercase_			,   has_text_modality=lowercase_ )






      def        lowerCamelCase       (					self						:     List[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        lowerCamelCase       (					self						:     int )					->						Optional[Any]:
             """simple docstring"""




             return






      def        lowerCamelCase       (					self						:     int )					->						List[str]:
             """simple docstring"""




             _lowerCamelCase       :		Tuple		=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_ )






      def        lowerCamelCase       (					self						:     Tuple )					->						str:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase_ )






      @unittest.skip(reason='RegNet does not use inputs_embeds' )
      def        lowerCamelCase       (					self						:     Any )					->						Union[str, Any]:
             """simple docstring"""




             pass






      @unittest.skip(reason='RegNet does not support input and output embeddings' )
      def        lowerCamelCase       (					self						:     List[Any] )					->						Dict:
             """simple docstring"""




             pass






      def        lowerCamelCase       (					self						:     str )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase	,     _lowerCamelCase       :		str		=self.model_tester.prepare_config_and_inputs_for_common()

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

                    _lowerCamelCase       :		str		=['pixel_values']
                    self.assertListEqual(arg_names[:1]			,   lowercase_ )






      def        lowerCamelCase       (					self						:     Dict )					->						Optional[int]:
             """simple docstring"""




             def check_hidden_states_output(lowercase_						:     List[str]			,   lowercase_						:     Any			,   lowercase_						:     Union[str, Any] ):
                    _lowerCamelCase       :		Optional[Any]		=model_class(lowercase_ )

                    _lowerCamelCase       :		List[str]		=model(**self._prepare_for_class(lowercase_			,   lowercase_ ) )

                    _lowerCamelCase       :		int		=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                    _lowerCamelCase       :		Optional[Any]		=self.model_tester.num_stages
                    self.assertEqual(len(lowercase_ )			,   expected_num_stages + 1 )

             _lowerCamelCase	,     _lowerCamelCase       :		List[str]		=self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _lowerCamelCase       :		Any		=True
                    check_hidden_states_output(lowercase_			,   lowercase_			,   lowercase_ )

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    _lowerCamelCase       :		Optional[int]		=True

                    check_hidden_states_output(lowercase_			,   lowercase_			,   lowercase_ )






      def        lowerCamelCase       (					self						:     Any )					->						List[Any]:
             """simple docstring"""




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

             for model_class in self.all_model_classes:
                    with self.subTest(model_class.__name__ ):
                           _lowerCamelCase       :		Optional[Any]		=self._prepare_for_class(lowercase_			,   lowercase_ )
                           _lowerCamelCase       :		Optional[Any]		=model_class(lowercase_ )

                           @jax.jit
                           def model_jitted(lowercase_						:     Tuple			,   **lowercase_						:     Any ):
                                  return model(pixel_values=lowercase_			,   **lowercase_ )

                           with self.subTest('JIT Enabled' ):
                                  _lowerCamelCase       :		Any		=model_jitted(**lowercase_ ).to_tuple()

                           with self.subTest('JIT Disabled' ):
                                  with jax.disable_jit():
                                         _lowerCamelCase       :		Union[str, Any]		=model_jitted(**lowercase_ ).to_tuple()

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




def 	a_      (    ):
       '''simple docstring'''





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




@require_flax
class A  (   unittest.TestCase     ):






      @cached_property
      def        lowerCamelCase       (					self						:     Optional[Any] )					->						Optional[Any]:
             """simple docstring"""




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






      @slow
      def        lowerCamelCase       (					self						:     Dict )					->						Any:
             """simple docstring"""




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

             _lowerCamelCase       :		List[Any]		=self.default_image_processor
             _lowerCamelCase       :		Optional[int]		=prepare_img()
             _lowerCamelCase       :		int		=image_processor(images=lowercase_			,   return_tensors='np' )

             _lowerCamelCase       :		Optional[int]		=model(**lowercase_ )

             # verify the logits
             _lowerCamelCase       :		List[str]		=(1, 1000)
             self.assertEqual(outputs.logits.shape			,   lowercase_ )

             _lowerCamelCase       :		Dict		=jnp.array([-0.4180, -1.5051, -3.4836] )

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






import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


lowerCamelCase											=       logging.getLogger()




@unittest.skip('Temporarily disable the doc tests.'     )
@require_torch
@require_tf
@slow
class A  (   unittest.TestCase     ):






      def        lowerCamelCase       (					self						:     Dict			,   lowercase_						:     Path			,   lowercase_						:     Union[str, None] = None			,   lowercase_						:     Union[List[str], None] = None			,   lowercase_						:     Union[str, List[str], None] = None			,   lowercase_						:     bool = True			,   )					->						Optional[int]:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=[file for file in os.listdir(lowercase_ ) if os.path.isfile(os.path.join(lowercase_			,   lowercase_ ) )]

             if identifier is not None:
                    _lowerCamelCase       :		Any		=[file for file in files if identifier in file]

             if n_identifier is not None:
                    if isinstance(lowercase_			,   lowercase_ ):
                           for n_ in n_identifier:
                                  _lowerCamelCase       :		Any		=[file for file in files if n_ not in file]
                    else:
                           _lowerCamelCase       :		List[Any]		=[file for file in files if n_identifier not in file]

             _lowerCamelCase       :		List[Any]		=ignore_files or []
             ignore_files.append('__init__.py' )
             _lowerCamelCase       :		List[Any]		=[file for file in files if file not in ignore_files]

             for file in files:
                    # Open all files
                    print('Testing'			,   lowercase_ )

                    if only_modules:
                           _lowerCamelCase       :		Optional[int]		=file.split('.' )[0]
                           try:
                                  _lowerCamelCase       :		Any		=getattr(lowercase_			,   lowercase_ )
                                  _lowerCamelCase       :		Optional[int]		=doctest.DocTestSuite(lowercase_ )
                                  _lowerCamelCase       :		List[Any]		=unittest.TextTestRunner().run(lowercase_ )
                                  self.assertIs(len(result.failures )			,   0 )
                           except AttributeError:
                                  logger.info(F'''{module_identifier} is not a module.''' )
                    else:
                           _lowerCamelCase       :		int		=doctest.testfile(str('..' / directory / file )			,   optionflags=doctest.ELLIPSIS )
                           self.assertIs(result.failed			,   0 )






      def        lowerCamelCase       (					self						:     Any )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		int		=Path('src/transformers' )
             _lowerCamelCase       :		Optional[Any]		='modeling'
             _lowerCamelCase       :		List[str]		=[
                 'modeling_ctrl.py',
                 'modeling_tf_ctrl.py',
             ]
             self.analyze_directory(lowercase_			,   identifier=lowercase_			,   ignore_files=lowercase_ )






      def        lowerCamelCase       (					self						:     List[str] )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=Path('src/transformers' )
             _lowerCamelCase       :		Union[str, Any]		='tokenization'
             self.analyze_directory(lowercase_			,   identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     Optional[int] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		str		=Path('src/transformers' )
             _lowerCamelCase       :		Any		='configuration'
             self.analyze_directory(lowercase_			,   identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     List[str] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=Path('src/transformers' )
             _lowerCamelCase       :		int		=['configuration', 'modeling', 'tokenization']
             self.analyze_directory(lowercase_			,   n_identifier=lowercase_ )






      def        lowerCamelCase       (					self						:     Optional[Any] )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		str		=Path('docs/source' )
             _lowerCamelCase       :		Dict		=['favicon.ico']
             self.analyze_directory(lowercase_			,   ignore_files=lowercase_			,   only_modules=lowercase_ )


