





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 ):


  def __init__(							self ,__snake_case ,__snake_case=3 ,__snake_case=3_2 ,__snake_case=3 ,__snake_case=1_0 ,__snake_case=[1_0, 2_0, 3_0, 4_0] ,__snake_case=[1, 1, 2, 1] ,__snake_case=True ,__snake_case=True ,__snake_case="relu" ,__snake_case=3 ,__snake_case=None ,):



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


  def 						__UpperCAmelCase     (							self ):



       """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 						__UpperCAmelCase     (							self ):



       """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 ,__snake_case ,__snake_case ):



       """simple docstring"""





       A_          =       FlaxRegNetModel(config=__snake_case )
       A_          =       model(__snake_case )

       # 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 ,__snake_case ,__snake_case ):



       """simple docstring"""





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




  def 						__UpperCAmelCase     (							self ):



       """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_				( _SCREAMING_SNAKE_CASE     ,		unittest.TestCase ):
  __lowerCAmelCase   :						Tuple							=   (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

  __lowerCAmelCase   :						Optional[int]							=   False
  __lowerCAmelCase   :						List[Any]							=   False
  __lowerCAmelCase   :						Optional[int]							=   False


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       FlaxRegNetModelTester(self )
       A_          =       ConfigTester(self ,config_class=__snake_case ,has_text_modality=__snake_case )


  def 						__UpperCAmelCase     (							self ):



       """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 ):



       """simple docstring"""





       return


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__snake_case )


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__snake_case )


  @unittest.skip(reason='''RegNet does not use inputs_embeds''' )
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       pass


  @unittest.skip(reason='''RegNet does not support input and output embeddings''' )
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       pass


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_   ,    A_          =       self.model_tester.prepare_config_and_inputs_for_common()

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


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       def check_hidden_states_output(__snake_case ,__snake_case ,__snake_case ):
            A_          =       model_class(__snake_case )

            A_          =       model(**self._prepare_for_class(__snake_case ,__snake_case ) )

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

            A_          =       self.model_tester.num_stages
            self.assertEqual(len(__snake_case ) ,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(__snake_case ,__snake_case ,__snake_case )

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

            check_hidden_states_output(__snake_case ,__snake_case ,__snake_case )




  def 						__UpperCAmelCase     (							self ):



       """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(__snake_case ,__snake_case )
                 A_          =       model_class(__snake_case )

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

                 with self.subTest('''JIT Enabled''' ):
                      A_          =       model_jitted(**__snake_case ).to_tuple()

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

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




def      UpperCAmelCase_    (    )	->				str:
     '''simple docstring'''


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





@require_flax
class UpperCAmelCase_				( unittest.TestCase ):


  @cached_property
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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




  @slow
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





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

       A_          =       self.default_image_processor
       A_          =       prepare_img()
       A_          =       image_processor(images=__snake_case ,return_tensors='''np''' )

       A_          =       model(**__snake_case )

       # verify the logits
       A_          =       (1, 1_0_0_0)
       self.assertEqual(outputs.logits.shape ,__snake_case )

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

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










import logging
import os
import threading
import time


try:
      import warnings
except ImportError:
      a__      :     Optional[Any]         =		None

try:
      import msvcrt
except ImportError:
      a__      :     List[str]         =		None

try:
      import fcntl
except ImportError:
      a__      :     Optional[int]         =		None


# Backward compatibility
# ------------------------------------------------
try:
      TimeoutError
except NameError:
      a__      :     List[str]         =		OSError


# Data
# ------------------------------------------------
a__      :     Union[str, Any]         =		[
    'Timeout',
    'BaseFileLock',
    'WindowsFileLock',
    'UnixFileLock',
    'SoftFileLock',
    'FileLock',
]

a__      :     str         =		'3.0.12'


a__      :     Optional[int]         =		None

def      UpperCAmelCase_    (    )	->				Tuple:
     '''simple docstring'''


     global _logger
     A_          =       _logger or logging.getLogger(__name__				)
     return _logger





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):


  def __init__(							self ,__snake_case ):



       """simple docstring"""





       A_          =       lock_file
       return None




  def __str__(							self ):



       """simple docstring"""





       A_          =       f'The file lock \'{self.lock_file}\' could not be acquired.'
       return temp





class UpperCAmelCase_				:


  def __init__(							self ,__snake_case ):



       """simple docstring"""





       A_          =       lock
       return None


  def __enter__(							self ):



       """simple docstring"""





       return self.lock




  def __exit__(							self ,__snake_case ,__snake_case ,__snake_case ):



       """simple docstring"""





       self.lock.release()
       return None





class UpperCAmelCase_				:


  def __init__(							self ,__snake_case ,__snake_case=-1 ,__snake_case=None ):



       """simple docstring"""





       A_          =       max_filename_length if max_filename_length is not None else 2_5_5
       # Hash the filename if it's too long
       A_          =       self.hash_filename_if_too_long(__snake_case ,__snake_case )
       # The path to the lock file.
       A_          =       lock_file

       # The file descriptor for the *_lock_file* as it is returned by the
       # os.open() function.
       # This file lock is only NOT None, if the object currently holds the
       # lock.
       A_          =       None

       # The default timeout value.
       A_          =       timeout

       # We use this lock primarily for the lock counter.
       A_          =       threading.Lock()

       # The lock counter is used for implementing the nested locking
       # mechanism. Whenever the lock is acquired, the counter is increased and
       # the lock is only released, when this value is 0 again.
       A_          =       0
       return None


  @property
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       return self._lock_file


  @property
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       return self._timeout


  @timeout.setter
  def 						__UpperCAmelCase     (							self ,__snake_case ):



       """simple docstring"""





       A_          =       float(__snake_case )
       return None


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       raise NotImplementedError()


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       raise NotImplementedError()


  @property
  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       return self._lock_file_fd is not None


  def 						__UpperCAmelCase     (							self ,__snake_case=None ,__snake_case=0.05 ):



       """simple docstring"""





       if timeout is None:
            A_          =       self.timeout

       # Increment the number right at the beginning.
       # We can still undo it, if something fails.
       with self._thread_lock:
            self._lock_counter += 1

       A_          =       id(self )
       A_          =       self._lock_file
       A_          =       time.time()
       try:
            while True:
                 with self._thread_lock:
                      if not self.is_locked:
                           logger().debug(f'Attempting to acquire lock {lock_id} on {lock_filename}' )
                           self._acquire()

                 if self.is_locked:
                      logger().debug(f'Lock {lock_id} acquired on {lock_filename}' )
                      break
                 elif timeout >= 0 and time.time() - start_time > timeout:
                      logger().debug(f'Timeout on acquiring lock {lock_id} on {lock_filename}' )
                      raise Timeout(self._lock_file )
                 else:
                      logger().debug(
                          f'Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...' )
                      time.sleep(__snake_case )
       except:  # noqa
            # Something did go wrong, so decrement the counter.
            with self._thread_lock:
                 A_          =       max(0 ,self._lock_counter - 1 )

            raise
       return _Acquire_ReturnProxy(lock=self )


  def 						__UpperCAmelCase     (							self ,__snake_case=False ):



       """simple docstring"""





       with self._thread_lock:
            if self.is_locked:
                 self._lock_counter -= 1

                 if self._lock_counter == 0 or force:
                      A_          =       id(self )
                      A_          =       self._lock_file

                      logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}' )
                      self._release()
                      A_          =       0
                      logger().debug(f'Lock {lock_id} released on {lock_filename}' )

       return None


  def __enter__(							self ):



       """simple docstring"""





       self.acquire()
       return self


  def __exit__(							self ,__snake_case ,__snake_case ,__snake_case ):



       """simple docstring"""





       self.release()
       return None


  def __del__(							self ):



       """simple docstring"""





       self.release(force=__snake_case )
       return None




  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ):



       """simple docstring"""





       A_          =       os.path.basename(__snake_case )
       if len(__snake_case ) > max_length and max_length > 0:
            A_          =       os.path.dirname(__snake_case )
            A_          =       str(hash(__snake_case ) )
            A_          =       filename[: max_length - len(__snake_case ) - 8] + '''...''' + hashed_filename + '''.lock'''
            return os.path.join(__snake_case ,__snake_case )
       else:
            return path





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):


  def __init__(							self ,__snake_case ,__snake_case=-1 ,__snake_case=None ):



       """simple docstring"""





       from .file_utils import relative_to_absolute_path

       super().__init__(__snake_case ,timeout=__snake_case ,max_filename_length=__snake_case )
       A_          =       '''\\\\?\\''' + relative_to_absolute_path(self.lock_file )


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       os.O_RDWR | os.O_CREAT | os.O_TRUNC

       try:
            A_          =       os.open(self._lock_file ,__snake_case )
       except OSError:
            pass
       else:
            try:
                 msvcrt.locking(__snake_case ,msvcrt.LK_NBLCK ,1 )
            except OSError:
                 os.close(__snake_case )
            else:
                 A_          =       fd
       return None




  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       self._lock_file_fd
       A_          =       None
       msvcrt.locking(__snake_case ,msvcrt.LK_UNLCK ,1 )
       os.close(__snake_case )

       try:
            os.remove(self._lock_file )
       # Probably another instance of the application
       # that acquired the file lock.
       except OSError:
            pass
       return None





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):


  def __init__(							self ,__snake_case ,__snake_case=-1 ,__snake_case=None ):



       """simple docstring"""





       A_          =       os.statvfs(os.path.dirname(__snake_case ) ).f_namemax
       super().__init__(__snake_case ,timeout=__snake_case ,max_filename_length=__snake_case )


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       os.O_RDWR | os.O_CREAT | os.O_TRUNC
       A_          =       os.open(self._lock_file ,__snake_case )

       try:
            fcntl.flock(__snake_case ,fcntl.LOCK_EX | fcntl.LOCK_NB )
       except OSError:
            os.close(__snake_case )
       else:
            A_          =       fd
       return None




  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       self._lock_file_fd
       A_          =       None
       fcntl.flock(__snake_case ,fcntl.LOCK_UN )
       os.close(__snake_case )
       return None





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       A_          =       os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
       try:
            A_          =       os.open(self._lock_file ,__snake_case )
       except OSError:
            pass
       else:
            A_          =       fd
       return None




  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       os.close(self._lock_file_fd )
       A_          =       None

       try:
            os.remove(self._lock_file )
       # The file is already deleted and that's what we want.
       except OSError:
            pass
       return None




a__      :     Union[str, Any]         =		None

if msvcrt:
      a__      :     Dict         =		WindowsFileLock
elif fcntl:
      a__      :     Dict         =		UnixFileLock
else:
      a__      :     Optional[int]         =		SoftFileLock

      if warnings is not None:
            warnings.warn('only soft file lock is available')



