"""simple docstring"""
import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import RegNetForImageClassification, RegNetModel
 from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class        __snake_case	:



      def __init__(						self   ,      lowercase   ,      lowercase=3   ,      lowercase=32   ,      lowercase=3   ,      lowercase=10   ,      lowercase=[10, 20, 30, 40]   ,      lowercase=[1, 1, 2, 1]   ,      lowercase=True   ,      lowercase=True   ,      lowercase="relu"   ,      lowercase=3   ,      lowercase=None   ,      )     ->      Any:





        '''simple docstring'''





        a__:					Union[str, Any]      							=     parent
        a__:					int      							=     batch_size
        a__:					List[Any]      							=     image_size
        a__:					Any      							=     num_channels
        a__:					Dict      							=     embeddings_size
        a__:					str      							=     hidden_sizes
        a__:					List[Any]      							=     depths
        a__:					Optional[int]      							=     is_training
        a__:					Optional[int]      							=     use_labels
        a__:					Tuple      							=     hidden_act
        a__:					Any      							=     num_labels
        a__:					Union[str, Any]      							=     scope
        a__:					Tuple      							=     len(lowercase)



      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        a__:					Optional[int]      							=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

        a__:					str      							=     None
        if self.use_labels:
          a__:					Dict      							=     ids_tensor([self.batch_size]   ,      self.num_labels)

        a__:					int      							=     self.get_config()

        return config, pixel_values, labels



      def   lowerCamelCase_       (						self)     ->      Optional[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   ,      )



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase   ,      lowercase)     ->      Any:





        '''simple docstring'''





        a__:					Dict      							=     RegNetModel(config=lowercase)
        model.to(lowercase)
        model.eval()
        a__:					List[str]      							=     model(lowercase)
        # expected last hidden states: B, C, H // 32, W // 32
        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   ,      lowercase   ,      lowercase   ,      lowercase)     ->      List[Any]:





        '''simple docstring'''





        a__:					Tuple      							=     self.num_labels
        a__:					Tuple      							=     RegNetForImageClassification(lowercase)
        model.to(lowercase)
        model.eval()
        a__:					Any      							=     model(lowercase   ,      labels=lowercase)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels))



      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





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







@require_torch
class        __snake_case	(					__lowerCAmelCase	,				__lowerCAmelCase	,				unittest.TestCase    ):
      a__				=		(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
      a__				=		(
          {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
          if is_torch_available()
          else {}
      )

      a__				=		False
      a__				=		False
      a__				=		False
      a__				=		False



      def   lowerCamelCase_       (						self)     ->      Dict:





        '''simple docstring'''





        a__:					Dict      							=     RegNetModelTester(self)
        a__:					Dict      							=     ConfigTester(self   ,      config_class=lowercase   ,      has_text_modality=lowercase)



      def   lowerCamelCase_       (						self)     ->      Dict:





        '''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)     ->      Optional[Any]:





        '''simple docstring'''





        return



      @unittest.skip(reason='RegNet does not use inputs_embeds')
      def   lowerCamelCase_       (						self)     ->      List[str]:





        '''simple docstring'''





        pass



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





        '''simple docstring'''





        pass



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





        '''simple docstring'''





        a__:					str      							=     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__:					int      							=     model_class(lowercase)
          a__:					str      							=     inspect.signature(model.forward)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          a__:					int      							=     [*signature.parameters.keys()]

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



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





        '''simple docstring'''





        a__:					Any      							=     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase)



      def   lowerCamelCase_       (						self)     ->      Dict:





        '''simple docstring'''





        a__:					int      							=     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__:					int      							=     model_class(config=lowercase)
          for name, module in model.named_modules():
            if isinstance(lowercase   ,      (nn.BatchNormad, nn.GroupNorm)):
              self.assertTrue(
                  torch.all(module.weight == 1)   ,      msg=f'Parameter {name} of model {model_class} seems not properly initialized'   ,      )
              self.assertTrue(
                  torch.all(module.bias == 0)   ,      msg=f'Parameter {name} of model {model_class} seems not properly initialized'   ,      )



      def   lowerCamelCase_       (						self)     ->      Optional[int]:





        '''simple docstring'''





        def check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase):
          a__:					int      							=     model_class(lowercase)
          model.to(lowercase)
          model.eval()

          with torch.no_grad():
            a__:					int      							=     model(**self._prepare_for_class(lowercase   ,      lowercase))

          a__:					Any      							=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          a__:					List[str]      							=     self.model_tester.num_stages
          self.assertEqual(len(lowercase)   ,      expected_num_stages + 1)

          # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
          self.assertListEqual(
              list(hidden_states[0].shape[-2:])   ,      [self.model_tester.image_size // 2, self.model_tester.image_size // 2]   ,      )

        a__:					Optional[Any]      							=     self.model_tester.prepare_config_and_inputs_for_common()
        a__:					Dict      							=     ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            a__:					Dict      							=     layer_type
            a__:					Dict      							=     True
            check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase)

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

            check_hidden_states_output(lowercase   ,      lowercase   ,      lowercase)



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





        '''simple docstring'''





        a__:					Optional[Any]      							=     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase)



      @slow
      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__:					Tuple      							=     RegNetModel.from_pretrained(lowercase)
          self.assertIsNotNone(lowercase)







def 						__a       (     )     ->Dict:
  a__:					str      							=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
  return image




@require_torch
@require_vision
class        __snake_case	(					unittest.TestCase    ):



      @cached_property
      def   lowerCamelCase_       (						self)     ->      Any:





        '''simple docstring'''





        return (
            AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])
            if is_vision_available()
            else None
        )



      @slow
      def   lowerCamelCase_       (						self)     ->      Optional[int]:





        '''simple docstring'''





        a__:					Tuple      							=     RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(lowercase)

        a__:					Tuple      							=     self.default_image_processor
        a__:					str      							=     prepare_img()
        a__:					Optional[int]      							=     image_processor(images=lowercase   ,      return_tensors='pt').to(lowercase)

        # forward pass
        with torch.no_grad():
          a__:					List[Any]      							=     model(**lowercase)

        # verify the logits
        a__:					Tuple      							=     torch.Size((1, 10_00))
        self.assertEqual(outputs.logits.shape   ,      lowercase)

        a__:					Optional[Any]      							=     torch.tensor([-0.4180, -1.5051, -3.4836]).to(lowercase)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,      lowercase   ,      atol=1e-4))



"""simple docstring"""
import logging
import os
import threading
import time


try:
 import warnings
except ImportError:
 lowercase__ 	=     None

try:
 import msvcrt
except ImportError:
 lowercase__ 	=     None

try:
 import fcntl
except ImportError:
 lowercase__ 	=     None


# Backward compatibility
# ------------------------------------------------
try:
 TimeoutError
except NameError:
 lowercase__ 	=     OSError


# Data
# ------------------------------------------------
lowercase__ 	=     [
    'Timeout',
    'BaseFileLock',
    'WindowsFileLock',
    'UnixFileLock',
    'SoftFileLock',
    'FileLock',
]

lowercase__ 	=     '3.0.12'


lowercase__ 	=     None







def 						__a       (     )     ->List[Any]:
  global _logger
  a__:					str      							=     _logger or logging.getLogger(__name__       )
  return _logger




class        __snake_case	(					__lowerCAmelCase    ):



      def __init__(						self   ,      lowercase)     ->      Any:





        '''simple docstring'''





        a__:					List[Any]      							=     lock_file
        return None



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





        '''simple docstring'''





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







class        __snake_case	:



      def __init__(						self   ,      lowercase)     ->      Union[str, Any]:





        '''simple docstring'''





        a__:					Any      							=     lock
        return None



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





        '''simple docstring'''





        return self.lock



      def __exit__(						self   ,      lowercase   ,      lowercase   ,      lowercase)     ->      int:





        '''simple docstring'''





        self.lock.release()
        return None







class        __snake_case	:



      def __init__(						self   ,      lowercase   ,      lowercase=-1   ,      lowercase=None)     ->      Dict:





        '''simple docstring'''





        a__:					Union[str, Any]      							=     max_filename_length if max_filename_length is not None else 2_55
        # Hash the filename if it's too long
        a__:					Tuple      							=     self.hash_filename_if_too_long(lowercase   ,      lowercase)
        # The path to the lock file.
        a__:					Any      							=     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__:					Dict      							=     None

        # The default timeout value.
        a__:					Union[str, Any]      							=     timeout

        # We use this lock primarily for the lock counter.
        a__:					Any      							=     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__:					Tuple      							=     0
        return None



      @property
      def   lowerCamelCase_       (						self)     ->      List[Any]:





        '''simple docstring'''





        return self._lock_file



      @property
      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        return self._timeout



      @timeout.setter
      def   lowerCamelCase_       (						self   ,      lowercase)     ->      List[str]:





        '''simple docstring'''





        a__:					Optional[int]      							=     float(lowercase)
        return None



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





        '''simple docstring'''





        raise NotImplementedError()



      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        raise NotImplementedError()



      @property
      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        return self._lock_file_fd is not None



      def   lowerCamelCase_       (						self   ,      lowercase=None   ,      lowercase=0.05)     ->      int:





        '''simple docstring'''





        if timeout is None:
          a__:					int      							=     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__:					Optional[int]      							=     id(self)
        a__:					Union[str, Any]      							=     self._lock_file
        a__:					Optional[int]      							=     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(lowercase)
        except:  # noqa
          # Something did go wrong, so decrement the counter.
          with self._thread_lock:
            a__:					Optional[int]      							=     max(0   ,      self._lock_counter - 1)

          raise
        return _Acquire_ReturnProxy(lock=self)



      def   lowerCamelCase_       (						self   ,      lowercase=False)     ->      Tuple:





        '''simple docstring'''





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

            if self._lock_counter == 0 or force:
              a__:					List[str]      							=     id(self)
              a__:					List[Any]      							=     self._lock_file

              logger().debug(f'Attempting to release lock {lock_id} on {lock_filename}')
              self._release()
              a__:					List[str]      							=     0
              logger().debug(f'Lock {lock_id} released on {lock_filename}')

        return None



      def __enter__(						self)     ->      Dict:





        '''simple docstring'''





        self.acquire()
        return self



      def __exit__(						self   ,      lowercase   ,      lowercase   ,      lowercase)     ->      List[str]:





        '''simple docstring'''





        self.release()
        return None



      def __del__(						self)     ->      Optional[int]:





        '''simple docstring'''





        self.release(force=lowercase)
        return None



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase)     ->      str:





        '''simple docstring'''





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







class        __snake_case	(					__lowerCAmelCase    ):



      def __init__(						self   ,      lowercase   ,      lowercase=-1   ,      lowercase=None)     ->      Dict:





        '''simple docstring'''





        from .file_utils import relative_to_absolute_path

        super().__init__(lowercase   ,      timeout=lowercase   ,      max_filename_length=lowercase)
        a__:					List[Any]      							=     '\\\\?\\' + relative_to_absolute_path(self.lock_file)



      def   lowerCamelCase_       (						self)     ->      Tuple:





        '''simple docstring'''





        a__:					str      							=     os.O_RDWR | os.O_CREAT | os.O_TRUNC

        try:
          a__:					Tuple      							=     os.open(self._lock_file   ,      lowercase)
        except OSError:
          pass
        else:
          try:
            msvcrt.locking(lowercase   ,      msvcrt.LK_NBLCK   ,      1)
          except OSError:
            os.close(lowercase)
          else:
            a__:					Dict      							=     fd
        return None



      def   lowerCamelCase_       (						self)     ->      Tuple:





        '''simple docstring'''





        a__:					int      							=     self._lock_file_fd
        a__:					Union[str, Any]      							=     None
        msvcrt.locking(lowercase   ,      msvcrt.LK_UNLCK   ,      1)
        os.close(lowercase)

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







class        __snake_case	(					__lowerCAmelCase    ):



      def __init__(						self   ,      lowercase   ,      lowercase=-1   ,      lowercase=None)     ->      Dict:





        '''simple docstring'''





        a__:					Union[str, Any]      							=     os.statvfs(os.path.dirname(lowercase)).f_namemax
        super().__init__(lowercase   ,      timeout=lowercase   ,      max_filename_length=lowercase)



      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        a__:					Optional[int]      							=     os.O_RDWR | os.O_CREAT | os.O_TRUNC
        a__:					int      							=     os.open(self._lock_file   ,      lowercase)

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



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





        '''simple docstring'''





        a__:					str      							=     self._lock_file_fd
        a__:					Tuple      							=     None
        fcntl.flock(lowercase   ,      fcntl.LOCK_UN)
        os.close(lowercase)
        return None







class        __snake_case	(					__lowerCAmelCase    ):



      def   lowerCamelCase_       (						self)     ->      Tuple:





        '''simple docstring'''





        a__:					int      							=     os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
        try:
          a__:					Optional[Any]      							=     os.open(self._lock_file   ,      lowercase)
        except OSError:
          pass
        else:
          a__:					Union[str, Any]      							=     fd
        return None



      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        os.close(self._lock_file_fd)
        a__:					int      							=     None

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







lowercase__ 	=     None

if msvcrt:
 lowercase__ 	=     WindowsFileLock
elif fcntl:
 lowercase__ 	=     UnixFileLock
else:
 lowercase__ 	=     SoftFileLock

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


