





'''simple docstring'''


import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 ResNetBackbone, ResNetForImageClassification, ResNetModel
       from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor
class    a_     :





     def __init__(				self	:      Dict			,   lowercase	:      List[Any]			,   lowercase	:      List[Any]=3			,   lowercase	:      Tuple=32			,   lowercase	:      str=3			,   lowercase	:      Any=10			,   lowercase	:      List[str]=[10, 20, 30, 40]			,   lowercase	:      Optional[Any]=[1, 1, 2, 1]			,   lowercase	:      Dict=True			,   lowercase	:      int=True			,   lowercase	:      Dict="relu"			,   lowercase	:      Any=3			,   lowercase	:      Union[str, Any]=None			,   lowercase	:      int=["stage2", "stage3", "stage4"]			,   lowercase	:      Union[str, Any]=[2, 3, 4]			,   ):





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				parent
        lowercase_    :str					    =				batch_size
        lowercase_    :str					    =				image_size
        lowercase_    :Optional[Any]					    =				num_channels
        lowercase_    :List[str]					    =				embeddings_size
        lowercase_    :str					    =				hidden_sizes
        lowercase_    :Tuple					    =				depths
        lowercase_    :Any					    =				is_training
        lowercase_    :Union[str, Any]					    =				use_labels
        lowercase_    :List[str]					    =				hidden_act
        lowercase_    :Union[str, Any]					    =				num_labels
        lowercase_    :Any					    =				scope
        lowercase_    :List[Any]					    =				len(_A		)
        lowercase_    :Tuple					    =				out_features
        lowercase_    :Tuple					    =				out_indices





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        lowercase_    :List[str]					    =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        lowercase_    :Dict					    =				None
        if self.use_labels:
           lowercase_    :Optional[int]					    =				ids_tensor([self.batch_size]			,   self.num_labels		)

        lowercase_    :Any					    =				self.get_config()

        return config, pixel_values, labels





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        return ResNetConfig(
            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			,   out_features=self.out_features			,   out_indices=self.out_indices			,   )





     def 							lowercase__   (				self	:      Dict			,   lowercase	:      str			,   lowercase	:      Optional[int]			,   lowercase	:      List[Any]		):





        """simple docstring"""




        lowercase_    :Any					    =				ResNetModel(config=_A		)
        model.to(_A		)
        model.eval()
        lowercase_    :List[Any]					    =				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 							lowercase__   (				self	:      Optional[int]			,   lowercase	:      int			,   lowercase	:      int			,   lowercase	:      int		):





        """simple docstring"""




        lowercase_    :Any					    =				self.num_labels
        lowercase_    :List[Any]					    =				ResNetForImageClassification(_A		)
        model.to(_A		)
        model.eval()
        lowercase_    :Optional[Any]					    =				model(_A			,   labels=_A		)
        self.parent.assertEqual(result.logits.shape			,   (self.batch_size, self.num_labels)		)





     def 							lowercase__   (				self	:      Any			,   lowercase	:      List[str]			,   lowercase	:      int			,   lowercase	:      List[Any]		):





        """simple docstring"""




        lowercase_    :str					    =				ResNetBackbone(config=_A		)
        model.to(_A		)
        model.eval()
        lowercase_    :List[str]					    =				model(_A		)

        # verify feature maps
        self.parent.assertEqual(len(result.feature_maps		)			,   len(config.out_features		)		)
        self.parent.assertListEqual(list(result.feature_maps[0].shape		)			,   [self.batch_size, self.hidden_sizes[1], 4, 4]		)

        # verify channels
        self.parent.assertEqual(len(model.channels		)			,   len(config.out_features		)		)
        self.parent.assertListEqual(model.channels			,   config.hidden_sizes[1:]		)

        # verify backbone works with out_features=None
        lowercase_    :Union[str, Any]					    =				None
        lowercase_    :Optional[int]					    =				ResNetBackbone(config=_A		)
        model.to(_A		)
        model.eval()
        lowercase_    :str					    =				model(_A		)

        # verify feature maps
        self.parent.assertEqual(len(result.feature_maps		)			,   1		)
        self.parent.assertListEqual(list(result.feature_maps[0].shape		)			,   [self.batch_size, self.hidden_sizes[-1], 1, 1]		)

        # verify channels
        self.parent.assertEqual(len(model.channels		)			,   1		)
        self.parent.assertListEqual(model.channels			,   [config.hidden_sizes[-1]]		)







     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Dict					    =				self.prepare_config_and_inputs()
        lowercase_    :Tuple					    =				config_and_inputs
        lowercase_    :Union[str, Any]					    =				{'pixel_values': pixel_values}
        return config, inputs_dict







@require_torch
class    a_     (       lowercase__			,		lowercase__			,		unittest.TestCase							):
     __A  				=    (
         (
             ResNetModel,
             ResNetForImageClassification,
             ResNetBackbone,
         )
         if is_torch_available()
         else ()
     )
     __A  				=    (
         {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
         if is_torch_available()
         else {}
     )

     __A  				=    True
     __A  				=    False
     __A  				=    False
     __A  				=    False
     __A  				=    False





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				ResNetModelTester(self		)
        lowercase_    :Any					    =				ConfigTester(self			,   config_class=_A			,   has_text_modality=_A		)





     def 							lowercase__   (				self	:      Optional[int]		):





        """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 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        return





     @unittest.skip(reason="ResNet does not use inputs_embeds"		)
     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        pass





     @unittest.skip(reason="ResNet does not support input and output embeddings"		)
     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        pass





     def 							lowercase__   (				self	:      Optional[Any]		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowercase_    :Optional[Any]					    =				model_class(_A		)
           lowercase_    :List[str]					    =				inspect.signature(model.forward		)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           lowercase_    :Dict					    =				[*signature.parameters.keys()]

           lowercase_    :int					    =				['pixel_values']
           self.assertListEqual(arg_names[:1]			,   _A		)





     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




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





     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :List[Any]					    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*_A		)





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :List[Any]					    =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowercase_    :List[Any]					    =				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 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        def check_hidden_states_output(lowercase	:      Optional[Any]			,   lowercase	:      Optional[Any]			,   lowercase	:      str		):
           lowercase_    :str					    =				model_class(_A		)
           model.to(_A		)
           model.eval()

           with torch.no_grad():
              lowercase_    :Any					    =				model(**self._prepare_for_class(_A			,   _A		)		)

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

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

           # ResNet'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 // 4, self.model_tester.image_size // 4]			,   )

        lowercase_    :Dict					    =				self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_    :int					    =				['basic', 'bottleneck']
        for model_class in self.all_model_classes:
           for layer_type in layers_type:
              lowercase_    :Any					    =				layer_type
              lowercase_    :str					    =				True
              check_hidden_states_output(_A			,   _A			,   _A		)

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

              check_hidden_states_output(_A			,   _A			,   _A		)





     @unittest.skip(reason="ResNet does not use feedforward chunking"		)
     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        pass





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    :List[str]					    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_A		)







     @slow
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase_    :Optional[Any]					    =				ResNetModel.from_pretrained(_A		)
           self.assertIsNotNone(_A		)







def 							UpperCAmelCase_						(		):
   lowercase_    :List[str]					    =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
   return image
@require_torch
@require_vision
class    a_     (       unittest.TestCase							):





     @cached_property
     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




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







     @slow
     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Any					    =				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_A		)

        lowercase_    :int					    =				self.default_image_processor
        lowercase_    :str					    =				prepare_img()
        lowercase_    :Optional[Any]					    =				image_processor(images=_A			,   return_tensors="pt"		).to(_A		)

        # forward pass
        with torch.no_grad():
           lowercase_    :Tuple					    =				model(**_A		)

        # verify the logits
        lowercase_    :Optional[Any]					    =				torch.Size((1, 1_000)		)
        self.assertEqual(outputs.logits.shape			,   _A		)

        lowercase_    :int					    =				torch.tensor([-11.10_69, -9.78_77, -8.37_77]		).to(_A		)

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







@require_torch
class    a_     (       lowercase__			,		unittest.TestCase							):
     __A  				=    (ResNetBackbone,) if is_torch_available() else ()
     __A  				=    False
     __A  				=    ResNetConfig





     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				ResNetModelTester(self		)









'''simple docstring'''


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


lowerCAmelCase      :  Any      							=logging.get_logger(__name__)
class    a_     (       _lowerCAmelCase							):
     __A  				=    ["pixel_values"]





     def __init__(				self	:      Tuple			,   lowercase	:      bool = True			,   lowercase	:      Dict[str, int] = None			,   lowercase	:      bool = True			,   lowercase	:      Dict[str, int] = None			,   lowercase	:      PILImageResampling = PILImageResampling.BICUBIC			,   lowercase	:      bool = True			,   lowercase	:      Union[int, float] = 1 / 255			,   lowercase	:      bool = True			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   **lowercase	:      int			,   ):





        """simple docstring"""




        super().__init__(**lowercase		)
        lowercase_    :Dict					    =				crop_size if crop_size is not None else {"height": 256, "width": 256}
        lowercase_    :str					    =				get_size_dict(lowercase			,   param_name="crop_size"		)
        lowercase_    :Optional[Any]					    =				size if size is not None else {"height": 224, "width": 224}
        lowercase_    :Union[str, Any]					    =				get_size_dict(lowercase		)

        lowercase_    :Union[str, Any]					    =				do_center_crop
        lowercase_    :str					    =				crop_size
        lowercase_    :List[str]					    =				do_resize
        lowercase_    :str					    =				size
        lowercase_    :Tuple					    =				resample
        lowercase_    :int					    =				do_rescale
        lowercase_    :Union[str, Any]					    =				rescale_factor
        lowercase_    :Tuple					    =				do_normalize
        lowercase_    :List[Any]					    =				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        lowercase_    :Optional[int]					    =				image_std if image_std is not None else IMAGENET_DEFAULT_STD





     def 							lowercase__   (				self	:      Any			,   lowercase	:      np.ndarray			,   lowercase	:      Dict[str, int]			,   lowercase	:      Optional[int] = None			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      List[Any]			,   ):





        """simple docstring"""




        lowercase_    :Dict					    =				self.size if size is None else size
        lowercase_    :Dict					    =				get_size_dict(lowercase		)
        lowercase_    :List[Any]					    =				get_size_dict(lowercase			,   param_name="crop_size"		)

        lowercase_    ,							lowercase_    :List[str]					    =				get_image_size(lowercase		)
        lowercase_    :List[str]					    =				min(lowercase			,   lowercase		)
        lowercase_    :Tuple					    =				(size["height"] / crop_size["height"]) * min_dim
        lowercase_    :int					    =				(size["width"] / crop_size["width"]) * min_dim
        return center_crop(lowercase			,   size=(cropped_height, cropped_width)			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      Union[str, Any]			,   lowercase	:      np.ndarray			,   lowercase	:      Dict[str, int]			,   lowercase	:      PILImageResampling = PIL.Image.BICUBIC			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      List[str]			,   ):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				get_size_dict(lowercase		)
        if "height" not in size or "width" not in size:
           raise ValueError(F'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'		)
        return resize(
            lowercase			,   size=(size["height"], size["width"])			,   resample=lowercase			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      List[str]			,   lowercase	:      np.ndarray			,   lowercase	:      Union[int, float]			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      Union[str, Any]			,   ):





        """simple docstring"""




        return rescale(lowercase			,   scale=lowercase			,   data_format=lowercase			,   **lowercase		)





     def 							lowercase__   (				self	:      List[str]			,   lowercase	:      np.ndarray			,   lowercase	:      Union[float, List[float]]			,   lowercase	:      Union[float, List[float]]			,   lowercase	:      Optional[Union[str, ChannelDimension]] = None			,   **lowercase	:      str			,   ):





        """simple docstring"""




        return normalize(lowercase			,   mean=lowercase			,   std=lowercase			,   data_format=lowercase			,   **lowercase		)







     def 							lowercase__   (				self	:      List[Any]			,   lowercase	:      ImageInput			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Dict[str, int]] = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Dict[str, int]] = None			,   lowercase	:      PILImageResampling = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[float] = None			,   lowercase	:      Optional[bool] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[float, List[float]]] = None			,   lowercase	:      Optional[Union[str, TensorType]] = None			,   lowercase	:      ChannelDimension = ChannelDimension.FIRST			,   **lowercase	:      Optional[Any]			,   ):





        """simple docstring"""




        lowercase_    :str					    =				do_center_crop if do_center_crop is not None else self.do_center_crop
        lowercase_    :Union[str, Any]					    =				crop_size if crop_size is not None else self.crop_size
        lowercase_    :Optional[Any]					    =				get_size_dict(lowercase			,   param_name="crop_size"		)
        lowercase_    :Union[str, Any]					    =				do_resize if do_resize is not None else self.do_resize
        lowercase_    :Any					    =				size if size is not None else self.size
        lowercase_    :List[Any]					    =				get_size_dict(lowercase		)
        lowercase_    :Optional[Any]					    =				resample if resample is not None else self.resample
        lowercase_    :Dict					    =				do_rescale if do_rescale is not None else self.do_rescale
        lowercase_    :List[Any]					    =				rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_    :str					    =				do_normalize if do_normalize is not None else self.do_normalize
        lowercase_    :Dict					    =				image_mean if image_mean is not None else self.image_mean
        lowercase_    :List[Any]					    =				image_std if image_std is not None else self.image_std

        lowercase_    :Any					    =				make_list_of_images(lowercase		)

        if not valid_images(lowercase		):
           raise ValueError(
               "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
               "torch.Tensor, tf.Tensor or jax.ndarray."		)

        if do_center_crop and crop_size is None:
           raise ValueError("If `do_center_crop` is set to `True`, `crop_size` must be provided."		)

        if do_resize and size is None:
           raise ValueError("Size must be specified if do_resize is True."		)

        if do_rescale and rescale_factor is None:
           raise ValueError("Rescale factor must be specified if do_rescale is True."		)

        if do_normalize and (image_mean is None or image_std is None):
           raise ValueError("Image mean and image standard deviation must be specified if do_normalize is True."		)

        # All transformations expect numpy arrays.
        lowercase_    :Optional[int]					    =				[to_numpy_array(lowercase		) for image in images]

        if do_center_crop:
           lowercase_    :str					    =				[self.center_crop(lowercase			,   lowercase			,   size=lowercase		) for image in images]

        if do_resize:
           lowercase_    :List[str]					    =				[self.resize(image=lowercase			,   size=lowercase			,   resample=lowercase		) for image in images]

        if do_rescale:
           lowercase_    :List[Any]					    =				[self.rescale(image=lowercase			,   scale=lowercase		) for image in images]

        if do_normalize:
           lowercase_    :Optional[Any]					    =				[self.normalize(image=lowercase			,   mean=lowercase			,   std=lowercase		) for image in images]

        lowercase_    :Optional[Any]					    =				[to_channel_dimension_format(lowercase			,   lowercase		) for image in images]

        lowercase_    :Union[str, Any]					    =				{"pixel_values": images}
        return BatchFeature(data=lowercase			,   tensor_type=lowercase		)


