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






 '''simple docstring'''






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







        '''simple docstring'''



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




 def 		__snake_case						(			self					:  Optional[int]):







        '''simple docstring'''



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

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

        lowerCAmelCase__     	=					self.get_config()

        return config, pixel_values, labels




 def 		__snake_case						(			self					:  int):







        '''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					:  Union[str, Any]			,    lowercase__					:  Union[str, Any]			,    lowercase__					:  Dict			,    lowercase__					:  str):







        '''simple docstring'''



        lowerCAmelCase__     	=					ResNetModel(config=UpperCAmelCase_)
        model.to(UpperCAmelCase_)
        model.eval()
        lowerCAmelCase__     	=					model(UpperCAmelCase_)
        # 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					:  List[str]			,    lowercase__					:  Optional[int]			,    lowercase__					:  Dict			,    lowercase__					:  Tuple):







        '''simple docstring'''



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




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







        '''simple docstring'''



        lowerCAmelCase__     	=					ResNetBackbone(config=UpperCAmelCase_)
        model.to(UpperCAmelCase_)
        model.eval()
        lowerCAmelCase__     	=					model(UpperCAmelCase_)

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

        # 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					:  Union[str, Any]):







        '''simple docstring'''



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






@require_torch
class 				a_ (						__UpperCAmelCase       ,     __UpperCAmelCase       ,     unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_	 =					(
     (
         ResNetModel,
         ResNetForImageClassification,
         ResNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase_	 =					(
     {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase_	 =					True
 UpperCAmelCase_	 =					False
 UpperCAmelCase_	 =					False
 UpperCAmelCase_	 =					False
 UpperCAmelCase_	 =					False




 def 		__snake_case						(			self					:  int):







        '''simple docstring'''



        lowerCAmelCase__     	=					ResNetModelTester(self)
        lowerCAmelCase__     	=					ConfigTester(self			,    config_class=UpperCAmelCase_			,    has_text_modality=UpperCAmelCase_)




 def 		__snake_case						(			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 		__snake_case						(			self					:  Tuple):







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







        '''simple docstring'''



        pass




 def 		__snake_case						(			self					:  Tuple):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.model_tester.prepare_config_and_inputs_for_common()

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

               lowerCAmelCase__     	=					['pixel_values']
               self.assertListEqual(arg_names[:1]			,    UpperCAmelCase_)




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







        '''simple docstring'''



        lowerCAmelCase__     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase_)




 def 		__snake_case						(			self					:  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*UpperCAmelCase_)




 def 		__snake_case						(			self					:  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.model_tester.prepare_config_and_inputs_for_common()

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







        '''simple docstring'''



        def check_hidden_states_output(lowercase__					:  List[Any]			,    lowercase__					:  Optional[Any]			,    lowercase__					:  Dict):
               lowerCAmelCase__     	=					model_class(UpperCAmelCase_)
               model.to(UpperCAmelCase_)
               model.eval()

               with torch.no_grad():
                      lowerCAmelCase__     	=					model(**self._prepare_for_class(UpperCAmelCase_			,    UpperCAmelCase_))

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

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

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

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

                      check_hidden_states_output(UpperCAmelCase_			,    UpperCAmelCase_			,    UpperCAmelCase_)




 @unittest.skip(reason='ResNet does not use feedforward chunking')
 def 		__snake_case						(			self					:  Dict):







        '''simple docstring'''



        pass




 def 		__snake_case						(			self					:  Dict):







        '''simple docstring'''



        lowerCAmelCase__     	=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)




 @slow
 def 		__snake_case						(			self					:  Tuple):







        '''simple docstring'''



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






def       __lowerCamelCase		(						):
       lowerCAmelCase__     	=					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
       return image
@require_torch
@require_vision
class 				a_ (						unittest.TestCase						):






 '''simple docstring'''






 @cached_property
 def 		__snake_case						(			self					:  Dict):







        '''simple docstring'''



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




 @slow
 def 		__snake_case						(			self					:  Tuple):







        '''simple docstring'''



        lowerCAmelCase__     	=					ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(UpperCAmelCase_)

        lowerCAmelCase__     	=					self.default_image_processor
        lowerCAmelCase__     	=					prepare_img()
        lowerCAmelCase__     	=					image_processor(images=UpperCAmelCase_			,    return_tensors='pt').to(UpperCAmelCase_)

        # forward pass
        with torch.no_grad():
               lowerCAmelCase__     	=					model(**UpperCAmelCase_)

        # verify the logits
        lowerCAmelCase__     	=					torch.Size((1, 1_000))
        self.assertEqual(outputs.logits.shape			,    UpperCAmelCase_)

        lowerCAmelCase__     	=					torch.tensor([-11.1_069, -9.7_877, -8.3_777]).to(UpperCAmelCase_)

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






@require_torch
class 				a_ (						__UpperCAmelCase       ,     unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_	 =					(ResNetBackbone,) if is_torch_available() else ()
 UpperCAmelCase_	 =					False
 UpperCAmelCase_	 =					ResNetConfig




 def 		__snake_case						(			self					:  int):







        '''simple docstring'''



        lowerCAmelCase__     	=					ResNetModelTester(self)


"""simple docstring"""

from __future__ import annotations
def 		UpperCAmelCase					(		a_			):





		'''simple docstring'''


		assert (
		    isinstance(a_,						a_			) and mask > 0
		), F"""mask needs to be positive integer, your input {mask}"""
		lowerCamelCase     :			Tuple		=    []
		lowerCamelCase     :			Tuple		=    mask

		while submask:
				all_submasks.append(a_			)
				lowerCamelCase     :			Optional[int]		=    (submask - 1) & mask

		return all_submasks


if __name__ == "__main__":
					import doctest

					doctest.testmod()






