





'''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     lowerCAmelCase__ :

       '''simple docstring'''

       def __init__( self					:				List[str]       ,     a__					:				Dict       ,     a__					:				List[Any]=3       ,     a__					:				str=32       ,     a__					:				List[Any]=3       ,     a__					:				str=10       ,     a__					:				List[Any]=[10, 20, 30, 40]       ,     a__					:				Dict=[1, 1, 2, 1]       ,     a__					:				Tuple=True       ,     a__					:				List[Any]=True       ,     a__					:				List[str]="relu"       ,     a__					:				List[Any]=3       ,     a__					:				Union[str, Any]=None       ,     ):
              UpperCAmelCase  =						parent
              UpperCAmelCase  =						batch_size
              UpperCAmelCase  =						image_size
              UpperCAmelCase  =						num_channels
              UpperCAmelCase  =						embeddings_size
              UpperCAmelCase  =						hidden_sizes
              UpperCAmelCase  =						depths
              UpperCAmelCase  =						is_training
              UpperCAmelCase  =						use_labels
              UpperCAmelCase  =						hidden_act
              UpperCAmelCase  =						num_labels
              UpperCAmelCase  =						scope
              UpperCAmelCase  =						len(a__						)

       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

              UpperCAmelCase  =						None
              if self.use_labels:
                     UpperCAmelCase  =						ids_tensor([self.batch_size]       ,     self.num_labels						)

              UpperCAmelCase  =						self.get_config()

              return config, pixel_values, labels

       def 			__snake_case      ( self					:				Any						):
              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 			__snake_case      ( self					:				Optional[int]       ,     a__					:				List[Any]       ,     a__					:				List[Any]       ,     a__					:				Tuple						):
              UpperCAmelCase  =						RegNetModel(config=a__						)
              model.to(a__						)
              model.eval()
              UpperCAmelCase  =						model(a__						)
              # 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 			__snake_case      ( self					:				int       ,     a__					:				List[Any]       ,     a__					:				Union[str, Any]       ,     a__					:				Union[str, Any]						):
              UpperCAmelCase  =						self.num_labels
              UpperCAmelCase  =						RegNetForImageClassification(a__						)
              model.to(a__						)
              model.eval()
              UpperCAmelCase  =						model(a__       ,     labels=a__						)
              self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)						)



       def 			__snake_case      ( self					:				Union[str, Any]						):
              UpperCAmelCase  =						self.prepare_config_and_inputs()
              UpperCAmelCase,					UpperCAmelCase,					UpperCAmelCase  =						config_and_inputs
              UpperCAmelCase  =						{'''pixel_values''': pixel_values}
              return config, inputs_dict






@require_torch
class     lowerCAmelCase__ (				UpperCAmelCase_      , UpperCAmelCase_      , unittest.TestCase    ):

       '''simple docstring'''
       _lowerCamelCase								=(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       _lowerCamelCase								=(
           {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       _lowerCamelCase								=False
       _lowerCamelCase								=False
       _lowerCamelCase								=False
       _lowerCamelCase								=False

       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						RegNetModelTester(self						)
              UpperCAmelCase  =						ConfigTester(self       ,     config_class=a__       ,     has_text_modality=a__						)

       def 			__snake_case      ( self					:				Tuple						):
              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 			__snake_case      ( self					:				Optional[int]						):
              return

       @unittest.skip(reason='''RegNet does not use inputs_embeds'''						)
       def 			__snake_case      ( self					:				Optional[int]						):
              pass

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

       def 			__snake_case      ( self					:				int						):
              UpperCAmelCase,					UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs_for_common()

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

                     UpperCAmelCase  =						['''pixel_values''']
                     self.assertListEqual(arg_names[:1]       ,     a__						)

       def 			__snake_case      ( self					:				Optional[int]						):
              UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*a__						)

       def 			__snake_case      ( self					:				Optional[Any]						):
              UpperCAmelCase,					UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCAmelCase  =						model_class(config=a__						)
                     for name, module in model.named_modules():
                            if isinstance(a__       ,     (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 			__snake_case      ( self					:				Dict						):
              def check_hidden_states_output(a__					:				List[Any]       ,     a__					:				List[Any]       ,     a__					:				str						):
                     UpperCAmelCase  =						model_class(a__						)
                     model.to(a__						)
                     model.eval()

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

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

                     UpperCAmelCase  =						self.model_tester.num_stages
                     self.assertEqual(len(a__						)       ,     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]       ,     )

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

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

                            check_hidden_states_output(a__       ,     a__       ,     a__						)

       def 			__snake_case      ( self					:				str						):
              UpperCAmelCase  =						self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*a__						)



       @slow
       def 			__snake_case      ( self					:				str						):
              for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCAmelCase  =						RegNetModel.from_pretrained(a__						)
                     self.assertIsNotNone(a__						)


def       __snake_case		( )							->     Dict:

       """simple docstring"""


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






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

       '''simple docstring'''

       @cached_property
       def 			__snake_case      ( self					:				int						):
              return (
                  AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
                  if is_vision_available()
                  else None
              )



       @slow
       def 			__snake_case      ( self					:				List[str]						):
              UpperCAmelCase  =						RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(a__						)

              UpperCAmelCase  =						self.default_image_processor
              UpperCAmelCase  =						prepare_img()
              UpperCAmelCase  =						image_processor(images=a__       ,     return_tensors='''pt'''						).to(a__						)

              # forward pass
              with torch.no_grad():
                     UpperCAmelCase  =						model(**a__						)

              # verify the logits
              UpperCAmelCase  =						torch.Size((1, 1000)						)
              self.assertEqual(outputs.logits.shape       ,     a__						)

              UpperCAmelCase  =						torch.tensor([-0.4_180, -1.5_051, -3.4_836]						).to(a__						)

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





import enum
import os
from hashlib import shaaaa
from typing import Optional

from .. import config
from .logging import get_logger


UpperCamelCase__		 =     get_logger(__name__)

class     __snake_case    (				enum.Enum  ):
       """simple docstring"""







       __SCREAMING_SNAKE_CASE				    =							"all_checks"
       __SCREAMING_SNAKE_CASE				    =							"basic_checks"
       __SCREAMING_SNAKE_CASE				    =							"no_checks"






class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""














def 						lowerCamelCase__      ( __A    :Optional[dict]	,__A    :dict	,__A    :Any=None		):


       """simple docstring"""




       if expected_checksums is None:
              logger.info("""Unable to verify checksums."""		)
              return
       if len(set(__A		) - set(__A		)		) > 0:
              raise ExpectedMoreDownloadedFiles(str(set(__A		) - set(__A		)		)		)
       if len(set(__A		) - set(__A		)		) > 0:
              raise UnexpectedDownloadedFile(str(set(__A		) - set(__A		)		)		)
       __snake_case       	=							[url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]]
       __snake_case       	=							""" for """ + verification_name if verification_name is not None else """"""
       if len(__A		) > 0:
              raise NonMatchingChecksumError(
                  F'Checksums didn\'t match{for_verification_name}:\n'
                  F'{bad_urls}\n'
                  """Set `verification_mode='no_checks'` to skip checksums verification and ignore this error"""		)
       logger.info("""All the checksums matched successfully""" + for_verification_name		)

class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""













class     __snake_case    (				snake_case__  ):
       """simple docstring"""














def 						lowerCamelCase__      ( __A    :Optional[dict]	,__A    :dict		):


       """simple docstring"""




       if expected_splits is None:
              logger.info("""Unable to verify splits sizes."""		)
              return
       if len(set(__A		) - set(__A		)		) > 0:
              raise ExpectedMoreSplits(str(set(__A		) - set(__A		)		)		)
       if len(set(__A		) - set(__A		)		) > 0:
              raise UnexpectedSplits(str(set(__A		) - set(__A		)		)		)
       __snake_case       	=							[
           {"""expected""": expected_splits[name], """recorded""": recorded_splits[name]}
           for name in expected_splits
           if expected_splits[name].num_examples != recorded_splits[name].num_examples
       ]
       if len(__A		) > 0:
              raise NonMatchingSplitsSizesError(str(__A		)		)
       logger.info("""All the splits matched successfully."""		)







def 						lowerCamelCase__      ( __A    :str	,__A    :bool = True		):


       """simple docstring"""




       if record_checksum:
              __snake_case       	=							shaaaa()
              with open(__A	,"""rb"""		) as f:
                     for chunk in iter(lambda: f.read(1 << 2_0		)	,b""""""		):
                            m.update(__A		)
                     __snake_case       	=							m.hexdigest()
       else:
              __snake_case       	=							None
       return {"num_bytes": os.path.getsize(__A		), "checksum": checksum}







def 						lowerCamelCase__      ( __A    :Optional[int]		):


       """simple docstring"""




       if dataset_size and config.IN_MEMORY_MAX_SIZE:
              return dataset_size < config.IN_MEMORY_MAX_SIZE
       else:
              return False

