

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







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







            """simple docstring"""







            __lowercase     						=parent
            __lowercase     						=batch_size
            __lowercase     						=image_size
            __lowercase     						=num_channels
            __lowercase     						=embeddings_size
            __lowercase     						=hidden_sizes
            __lowercase     						=depths
            __lowercase     						=is_training
            __lowercase     						=use_labels
            __lowercase     						=hidden_act
            __lowercase     						=num_labels
            __lowercase     						=scope
            __lowercase     						=len(_snake_case )
            __lowercase     						=out_features
            __lowercase     						=out_indices







       def      snake_case				(							self     :	Tuple ):







            """simple docstring"""







            __lowercase     						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

            __lowercase     						=self.get_config()

            return config, pixel_values, labels







       def      snake_case				(							self     :	Union[str, 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      snake_case				(							self     :	Optional[int]  , __lowercase     :	List[Any]  , __lowercase     :	Optional[int]  , __lowercase     :	str ):







            """simple docstring"""







            __lowercase     						=ResNetModel(config=_snake_case )
            model.to(_snake_case )
            model.eval()
            __lowercase     						=model(_snake_case )
            # 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     :	Tuple  , __lowercase     :	Any  , __lowercase     :	Optional[Any]  , __lowercase     :	Tuple ):







            """simple docstring"""







            __lowercase     						=self.num_labels
            __lowercase     						=ResNetForImageClassification(_snake_case )
            model.to(_snake_case )
            model.eval()
            __lowercase     						=model(_snake_case  , labels=_snake_case )
            self.parent.assertEqual(result.logits.shape  , (self.batch_size, self.num_labels) )







       def      snake_case				(							self     :	Any  , __lowercase     :	List[Any]  , __lowercase     :	Any  , __lowercase     :	Tuple ):







            """simple docstring"""







            __lowercase     						=ResNetBackbone(config=_snake_case )
            model.to(_snake_case )
            model.eval()
            __lowercase     						=model(_snake_case )

            # 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     						=None
            __lowercase     						=ResNetBackbone(config=_snake_case )
            model.to(_snake_case )
            model.eval()
            __lowercase     						=model(_snake_case )

            # 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      snake_case				(							self     :	Tuple ):







            """simple docstring"""







            __lowercase     						=self.prepare_config_and_inputs()
            __lowercase     						=config_and_inputs
            __lowercase     						={'pixel_values': pixel_values}
            return config, inputs_dict






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

       lowerCAmelCase_				=	True
       lowerCAmelCase_				=	False
       lowerCAmelCase_				=	False
       lowerCAmelCase_				=	False
       lowerCAmelCase_				=	False







       def      snake_case				(							self     :	int ):







            """simple docstring"""







            __lowercase     						=ResNetModelTester(self )
            __lowercase     						=ConfigTester(self  , config_class=_snake_case  , has_text_modality=_snake_case )







       def      snake_case				(							self     :	str ):







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







            """simple docstring"""







            return







       @unittest.skip(reason='ResNet does not use inputs_embeds' )
       def      snake_case				(							self     :	Optional[Any] ):







            """simple docstring"""







            pass







       @unittest.skip(reason='ResNet does not support input and output embeddings' )
       def      snake_case				(							self     :	List[Any] ):







            """simple docstring"""







            pass







       def      snake_case				(							self     :	str ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs_for_common()

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

                 __lowercase     						=['pixel_values']
                 self.assertListEqual(arg_names[:1]  , _snake_case )







       def      snake_case				(							self     :	Dict ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_snake_case )







       def      snake_case				(							self     :	Dict ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*_snake_case )







       def      snake_case				(							self     :	Optional[Any] ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __lowercase     						=model_class(config=_snake_case )
                 for name, module in model.named_modules():
                      if isinstance(_snake_case  , (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     :	Any ):







            """simple docstring"""







            def check_hidden_states_output(__lowercase     :	Optional[Any]  , __lowercase     :	int  , __lowercase     :	List[str] ):
                 __lowercase     						=model_class(_snake_case )
                 model.to(_snake_case )
                 model.eval()

                 with torch.no_grad():
                      __lowercase     						=model(**self._prepare_for_class(_snake_case  , _snake_case ) )

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

                 __lowercase     						=self.model_tester.num_stages
                 self.assertEqual(len(_snake_case )  , 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     						=self.model_tester.prepare_config_and_inputs_for_common()
            __lowercase     						=['basic', 'bottleneck']
            for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                      __lowercase     						=layer_type
                      __lowercase     						=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"]
                      __lowercase     						=True

                      check_hidden_states_output(_snake_case  , _snake_case  , _snake_case )







       @unittest.skip(reason='ResNet does not use feedforward chunking' )
       def      snake_case				(							self     :	Union[str, Any] ):







            """simple docstring"""







            pass







       def      snake_case				(							self     :	Dict ):







            """simple docstring"""







            __lowercase     						=self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_snake_case )







       @slow
       def      snake_case				(							self     :	str ):







            """simple docstring"""







            for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __lowercase     						=ResNetModel.from_pretrained(_snake_case )
                 self.assertIsNotNone(_snake_case )






def 			__UpperCamelCase							(		):






     '''simple docstring'''





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


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







       @cached_property
       def      snake_case				(							self     :	Any ):







            """simple docstring"""







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







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







            """simple docstring"""







            __lowercase     						=ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_snake_case )

            __lowercase     						=self.default_image_processor
            __lowercase     						=prepare_img()
            __lowercase     						=image_processor(images=_snake_case  , return_tensors='pt' ).to(_snake_case )

            # forward pass
            with torch.no_grad():
                 __lowercase     						=model(**_snake_case )

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

            __lowercase     						=torch.tensor([-11.1069, -9.7_8_7_7, -8.3_7_7_7] ).to(_snake_case )

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






@require_torch
class 					lowerCAmelCase							( lowerCAmelCase_				,     unittest.TestCase				):
       lowerCAmelCase_				=	(ResNetBackbone,) if is_torch_available() else ()
       lowerCAmelCase_				=	False
       lowerCAmelCase_				=	ResNetConfig







       def      snake_case				(							self     :	List[str] ):







            """simple docstring"""







            __lowercase     						=ResNetModelTester(self )





'''simple docstring'''

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCAmelCase							=					{
    '''configuration_videomae''': ['''VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VideoMAEConfig'''],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       UpperCAmelCase							=					[
           '''VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''VideoMAEForPreTraining''',
           '''VideoMAEModel''',
           '''VideoMAEPreTrainedModel''',
           '''VideoMAEForVideoClassification''',
       ]

try:
       if not is_vision_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       UpperCAmelCase							=					['''VideoMAEFeatureExtractor''']
       UpperCAmelCase							=					['''VideoMAEImageProcessor''']

if TYPE_CHECKING:
       from .configuration_videomae import VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP, VideoMAEConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_videomae import (
                  VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST,
                  VideoMAEForPreTraining,
                  VideoMAEForVideoClassification,
                  VideoMAEModel,
                  VideoMAEPreTrainedModel,
              )

       try:
              if not is_vision_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .feature_extraction_videomae import VideoMAEFeatureExtractor
              from .image_processing_videomae import VideoMAEImageProcessor

else:
       import sys

       UpperCAmelCase							=					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


