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     :



 '''simple docstring'''

 def __init__(	self				:						Optional[Any]				,	lowerCamelCase				:						List[Any]				,	lowerCamelCase				:						Any=3				,	lowerCamelCase				:						Dict=3_2				,	lowerCamelCase				:						int=3				,	lowerCamelCase				:						Optional[Any]=1_0				,	lowerCamelCase				:						Dict=[1_0, 2_0, 3_0, 4_0]				,	lowerCamelCase				:						Optional[Any]=[1, 1, 2, 1]				,	lowerCamelCase				:						Tuple=True				,	lowerCamelCase				:						List[str]=True				,	lowerCamelCase				:						Optional[Any]="relu"				,	lowerCamelCase				:						List[str]=3				,	lowerCamelCase				:						Optional[int]=None				,	lowerCamelCase				:						Tuple=["stage2", "stage3", "stage4"]				,	lowerCamelCase				:						Optional[Any]=[2, 3, 4]				,	)       ->							Optional[int]:
        _UpperCamelCase   :				int       =     parent
        _UpperCamelCase   :				str       =     batch_size
        _UpperCamelCase   :				List[Any]       =     image_size
        _UpperCamelCase   :				List[str]       =     num_channels
        _UpperCamelCase   :				str       =     embeddings_size
        _UpperCamelCase   :				Optional[int]       =     hidden_sizes
        _UpperCamelCase   :				Optional[Any]       =     depths
        _UpperCamelCase   :				List[Any]       =     is_training
        _UpperCamelCase   :				int       =     use_labels
        _UpperCamelCase   :				List[str]       =     hidden_act
        _UpperCamelCase   :				List[Any]       =     num_labels
        _UpperCamelCase   :				Optional[Any]       =     scope
        _UpperCamelCase   :				Optional[Any]       =     len(lowerCamelCase     )
        _UpperCamelCase   :				int       =     out_features
        _UpperCamelCase   :				Any       =     out_indices

 def     __snake_case    (	self				:						Tuple     )       ->							Optional[int]:
        _UpperCamelCase   :				List[str]       =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

        _UpperCamelCase   :				Union[str, Any]       =     None
        if self.use_labels:
               _UpperCamelCase   :				Tuple       =     ids_tensor([self.batch_size]				,	self.num_labels     )

        _UpperCamelCase   :				Dict       =     self.get_config()

        return config, pixel_values, labels

 def     __snake_case    (	self				:						Optional[int]     )       ->							Dict:
        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]				,	lowerCamelCase				:						Optional[int]				,	lowerCamelCase				:						Dict				,	lowerCamelCase				:						Union[str, Any]     )       ->							str:
        _UpperCamelCase   :				str       =     ResNetModel(config=lowerCamelCase     )
        model.to(lowerCamelCase     )
        model.eval()
        _UpperCamelCase   :				Any       =     model(lowerCamelCase     )
        # 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 // 3_2, self.image_size // 3_2)				,	)

 def     __snake_case    (	self				:						List[str]				,	lowerCamelCase				:						Tuple				,	lowerCamelCase				:						Union[str, Any]				,	lowerCamelCase				:						Dict     )       ->							List[Any]:
        _UpperCamelCase   :				Dict       =     self.num_labels
        _UpperCamelCase   :				List[Any]       =     ResNetForImageClassification(lowerCamelCase     )
        model.to(lowerCamelCase     )
        model.eval()
        _UpperCamelCase   :				str       =     model(lowerCamelCase				,	labels=lowerCamelCase     )
        self.parent.assertEqual(result.logits.shape				,	(self.batch_size, self.num_labels)     )

 def     __snake_case    (	self				:						List[str]				,	lowerCamelCase				:						int				,	lowerCamelCase				:						Optional[Any]				,	lowerCamelCase				:						Optional[int]     )       ->							Optional[Any]:
        _UpperCamelCase   :				str       =     ResNetBackbone(config=lowerCamelCase     )
        model.to(lowerCamelCase     )
        model.eval()
        _UpperCamelCase   :				int       =     model(lowerCamelCase     )

        # 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
        _UpperCamelCase   :				Union[str, Any]       =     None
        _UpperCamelCase   :				Tuple       =     ResNetBackbone(config=lowerCamelCase     )
        model.to(lowerCamelCase     )
        model.eval()
        _UpperCamelCase   :				Optional[int]       =     model(lowerCamelCase     )

        # 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				:						List[str]     )       ->							Dict:
        _UpperCamelCase   :				Optional[int]       =     self.prepare_config_and_inputs()
        _UpperCamelCase  ,					_UpperCamelCase  ,					_UpperCamelCase   :				int       =     config_and_inputs
        _UpperCamelCase   :				Tuple       =     {'pixel_values': pixel_values}
        return config, inputs_dict







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



 '''simple docstring'''
 _lowerCamelCase  :		Optional[Any] 			=       (
     (
         ResNetModel,
         ResNetForImageClassification,
         ResNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 _lowerCamelCase  :		int 			=       (
     {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCamelCase  :		int 			=       True
 _lowerCamelCase  :		int 			=       False
 _lowerCamelCase  :		Dict 			=       False
 _lowerCamelCase  :		List[Any] 			=       False
 _lowerCamelCase  :		Optional[int] 			=       False

 def     __snake_case    (	self				:						Dict     )       ->							List[str]:
        _UpperCamelCase   :				List[str]       =     ResNetModelTester(self     )
        _UpperCamelCase   :				Optional[Any]       =     ConfigTester(self				,	config_class=lowerCamelCase				,	has_text_modality=lowerCamelCase     )

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

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

 @unittest.skip(reason='ResNet does not support input and output embeddings'     )
 def     __snake_case    (	self				:						Optional[int]     )       ->							Union[str, Any]:
        pass

 def     __snake_case    (	self				:						Any     )       ->							Union[str, Any]:
        _UpperCamelCase  ,					_UpperCamelCase   :				Optional[Any]       =     self.model_tester.prepare_config_and_inputs_for_common()

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

               _UpperCamelCase   :				Dict       =     ['pixel_values']
               self.assertListEqual(arg_names[:1]				,	lowerCamelCase     )

 def     __snake_case    (	self				:						List[str]     )       ->							Optional[Any]:
        _UpperCamelCase   :				List[str]       =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase     )

 def     __snake_case    (	self				:						List[str]     )       ->							Dict:
        _UpperCamelCase   :				Dict       =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*lowerCamelCase     )

 def     __snake_case    (	self				:						List[str]     )       ->							Optional[Any]:
        _UpperCamelCase  ,					_UpperCamelCase   :				Tuple       =     self.model_tester.prepare_config_and_inputs_for_common()

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

               with torch.no_grad():
                      _UpperCamelCase   :				Any       =     model(**self._prepare_for_class(lowerCamelCase				,	lowerCamelCase     )     )

               _UpperCamelCase   :				List[str]       =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               _UpperCamelCase   :				List[str]       =     self.model_tester.num_stages
               self.assertEqual(len(lowerCamelCase     )				,	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]				,	)

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

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

                      check_hidden_states_output(lowerCamelCase				,	lowerCamelCase				,	lowerCamelCase     )

 @unittest.skip(reason='ResNet does not use feedforward chunking'     )
 def     __snake_case    (	self				:						List[str]     )       ->							List[Any]:
        pass

 def     __snake_case    (	self				:						Dict     )       ->							Union[str, Any]:
        _UpperCamelCase   :				Optional[int]       =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase     )

 @slow
 def     __snake_case    (	self				:						Optional[Any]     )       ->							List[Any]:
        for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _UpperCamelCase   :				Tuple       =     ResNetModel.from_pretrained(lowerCamelCase     )
               self.assertIsNotNone(lowerCamelCase     )







def SCREAMING_SNAKE_CASE (   ):
       _UpperCamelCase   :				Any       =     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     )       ->							List[str]:
        return (
            AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
            if is_vision_available()
            else None
        )

 @slow
 def     __snake_case    (	self				:						List[str]     )       ->							Optional[Any]:
        _UpperCamelCase   :				Optional[Any]       =     ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(lowerCamelCase     )

        _UpperCamelCase   :				List[str]       =     self.default_image_processor
        _UpperCamelCase   :				Union[str, Any]       =     prepare_img()
        _UpperCamelCase   :				Any       =     image_processor(images=lowerCamelCase				,	return_tensors='pt'     ).to(lowerCamelCase     )

        # forward pass
        with torch.no_grad():
               _UpperCamelCase   :				Tuple       =     model(**lowerCamelCase     )

        # verify the logits
        _UpperCamelCase   :				List[Any]       =     torch.Size((1, 1_0_0_0)     )
        self.assertEqual(outputs.logits.shape				,	lowerCamelCase     )

        _UpperCamelCase   :				int       =     torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]     ).to(lowerCamelCase     )

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







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



 '''simple docstring'''
 _lowerCamelCase  :		Union[str, Any] 			=       (ResNetBackbone,) if is_torch_available() else ()
 _lowerCamelCase  :		List[Any] 			=       False
 _lowerCamelCase  :		List[str] 			=       ResNetConfig

 def     __snake_case    (	self				:						Tuple     )       ->							Optional[Any]:
        _UpperCamelCase   :				Union[str, Any]       =     ResNetModelTester(self     )




from __future__ import annotations


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int						,  lowercase_:		int ):
       assert n > 1 and a > 0 and greatest_common_divisor(lowercase_						,  lowercase_ ) == 1
       ((_UpperCamelCase)  ,					(_UpperCamelCase)  ,					(_UpperCamelCase))   :				Optional[int]       =     extended_gcd(lowercase_						,  lowercase_ )  # Implemented below
       _UpperCamelCase   :				str       =     (b * s) % n
       return x


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       ((_UpperCamelCase)  ,					(_UpperCamelCase))   :				Union[str, Any]       =     extended_euclid(lowercase_						,  lowercase_ )  # Implemented below
       if b < 0:
              _UpperCamelCase   :				Union[str, Any]       =     (b % n + n) % n
       return b


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int						,  lowercase_:		int ):
       _UpperCamelCase   :				Union[str, Any]       =     invert_modulo(lowercase_						,  lowercase_ )
       _UpperCamelCase   :				str       =     (b * s) % n
       return x


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       assert a >= 0 and b >= 0

       if b == 0:
              _UpperCamelCase  ,					_UpperCamelCase  ,					_UpperCamelCase   :				Any       =     a, 1, 0
       else:
              ((_UpperCamelCase)  ,					(_UpperCamelCase)  ,					(_UpperCamelCase))   :				Dict       =     extended_gcd(lowercase_						,  a % b )
              _UpperCamelCase   :				List[str]       =     q
              _UpperCamelCase   :				Any       =     p - q * (a // b)

       assert a % d == 0 and b % d == 0
       assert d == a * x + b * y

       return (d, x, y)


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       if b == 0:
              return (1, 0)
       ((_UpperCamelCase)  ,					(_UpperCamelCase))   :				Optional[Any]       =     extended_euclid(lowercase_						,  a % b )
       _UpperCamelCase   :				List[Any]       =     a // b
       return (y, x - k * y)


def SCREAMING_SNAKE_CASE (   lowercase_:		int						,  lowercase_:		int ):
       if a < b:
              _UpperCamelCase  ,					_UpperCamelCase   :				Optional[int]       =     b, a

       while a % b != 0:
              _UpperCamelCase  ,					_UpperCamelCase   :				Union[str, Any]       =     b, a % b

       return b


if __name__ == "__main__":
 from doctest import testmod

 testmod(name='''modular_division''', verbose=True)
 testmod(name='''modular_division2''', verbose=True)
 testmod(name='''invert_modulo''', verbose=True)
 testmod(name='''extended_gcd''', verbose=True)
 testmod(name='''extended_euclid''', verbose=True)
 testmod(name='''greatest_common_divisor''', verbose=True)



