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





   def __init__(							self:    List[str]			,a:    Any			,a:    Dict=3			,a:    Dict=32			,a:    Dict=3			,a:    Optional[Any]=10			,a:    Any=[10, 20, 30, 40]			,a:    int=[1, 1, 2, 1]			,a:    str=True			,a:    Union[str, Any]=True			,a:    Optional[Any]="relu"			,a:    int=3			,a:    Dict=None			,a:    Optional[int]=["stage2", "stage3", "stage4"]			,a:    Optional[Any]=[2, 3, 4]			,):
    __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	)
    __UpperCAmelCase         =					out_features
    __UpperCAmelCase         =					out_indices





   def 			snake_case	(							self:    List[Any]	):
    __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:    Optional[Any]	):
    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:    Any			,a:    Optional[int]			,a:    Optional[Any]			,a:    List[Any]	):
    __UpperCAmelCase         =					ResNetModel(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:    List[Any]			,a:    Union[str, Any]			,a:    Dict			,a:    Any	):
    __UpperCAmelCase         =					self.num_labels
    __UpperCAmelCase         =					ResNetForImageClassification(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:    Optional[int]			,a:    str			,a:    Dict			,a:    Union[str, Any]	):
    __UpperCAmelCase         =					ResNetBackbone(config=a	)
    model.to(a	)
    model.eval()
    __UpperCAmelCase         =					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
    __UpperCAmelCase         =					None
    __UpperCAmelCase         =					ResNetBackbone(config=a	)
    model.to(a	)
    model.eval()
    __UpperCAmelCase         =					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 			snake_case	(							self:    str	):
    __UpperCAmelCase         =					self.prepare_config_and_inputs()
    __UpperCAmelCase  ,			__UpperCAmelCase  ,			__UpperCAmelCase         =					config_and_inputs
    __UpperCAmelCase         =					{'pixel_values': pixel_values}
    return config, inputs_dict




@require_torch
class   _lowercase(     _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:    Optional[int]	):
    __UpperCAmelCase         =					ResNetModelTester(self	)
    __UpperCAmelCase         =					ConfigTester(self			,config_class=a			,has_text_modality=a	)





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





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





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





   def 			snake_case	(							self:    Any	):
    __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:    Dict	):
    __UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*a	)





   def 			snake_case	(							self:    str	):
    __UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*a	)





   def 			snake_case	(							self:    str	):
    __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:    Optional[int]	):
    def check_hidden_states_output(a:    Dict			,a:    Any			,a:    Optional[Any]	):
     __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	)

     # 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         =					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	)





   @unittest.skip(reason='ResNet does not use feedforward chunking'	)
   def 			snake_case	(							self:    int	):
    pass





   def 			snake_case	(							self:    List[str]	):
    __UpperCAmelCase         =					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*a	)





   @slow
   def 			snake_case	(							self:    Tuple	):
    for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __UpperCAmelCase         =					ResNetModel.from_pretrained(a	)
     self.assertIsNotNone(a	)




def 						__snake_case (       ):
 __UpperCAmelCase         =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
 return image

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





   @cached_property
   def 			snake_case	(							self:    List[str]	):
    return (
        AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)
        if is_vision_available()
        else None
    )





   @slow
   def 			snake_case	(							self:    Any	):
    __UpperCAmelCase         =					ResNetForImageClassification.from_pretrained(RESNET_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([-11.1069, -9.7877, -8.3777]	).to(a	)

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




@require_torch
class   _lowercase(     _lowerCamelCase   ,unittest.TestCase				):
   __lowerCamelCase    =  (ResNetBackbone,) if is_torch_available() else ()
   __lowerCamelCase    =  False
   __lowerCamelCase    =  ResNetConfig





   def 			snake_case	(							self:    str	):
    __UpperCAmelCase         =					ResNetModelTester(self	)




'''simple docstring'''




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_UpperCamelCase				:		Any       			=		logging.get_logger(__name__)

_UpperCamelCase				:		Any       			=		{
    'apple/mobilevitv2-1.0': 'https://huggingface.co/apple/mobilevitv2-1.0/resolve/main/config.json',
}

class   _lowercase(     _lowerCamelCase				):



   """simple docstring"""





   __lowerCamelCase    =  '''mobilevitv2'''





   def __init__(							self:    Union[str, Any]			,a:    Optional[int]=3			,a:    Any=256			,a:    str=2			,a:    Any=2.0			,a:    Union[str, Any]="swish"			,a:    List[str]=3			,a:    List[str]=32			,a:    int=0.1			,a:    List[Any]=0.02			,a:    List[Any]=1e-5			,a:    Tuple=512			,a:    Optional[Any]=[6, 12, 18]			,a:    Dict=0.1			,a:    List[Any]=255			,a:    Union[str, Any]=[2, 4, 3]			,a:    str=[128, 192, 256]			,a:    int=1.0			,a:    Optional[int]=2			,a:    Optional[Any]=0.0			,a:    int=0.0			,**a:    Optional[Any]			,):
    super().__init__(**a	)

    __UpperCAmelCase         =					num_channels
    __UpperCAmelCase         =					image_size
    __UpperCAmelCase         =					patch_size
    __UpperCAmelCase         =					expand_ratio
    __UpperCAmelCase         =					hidden_act
    __UpperCAmelCase         =					conv_kernel_size
    __UpperCAmelCase         =					output_stride
    __UpperCAmelCase         =					initializer_range
    __UpperCAmelCase         =					layer_norm_eps
    __UpperCAmelCase         =					n_attn_blocks
    __UpperCAmelCase         =					base_attn_unit_dims
    __UpperCAmelCase         =					width_multiplier
    __UpperCAmelCase         =					ffn_multiplier
    __UpperCAmelCase         =					ffn_dropout
    __UpperCAmelCase         =					attn_dropout
    __UpperCAmelCase         =					classifier_dropout_prob

    # decode head attributes for semantic segmentation
    __UpperCAmelCase         =					aspp_out_channels
    __UpperCAmelCase         =					atrous_rates
    __UpperCAmelCase         =					aspp_dropout_prob
    __UpperCAmelCase         =					semantic_loss_ignore_index




class   _lowercase(     _lowerCamelCase				):



   """simple docstring"""





   __lowerCamelCase    =  version.parse('''1.11'''				)





   @property
   def 			snake_case	(							self:    Optional[int]	):
    return OrderedDict([('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'})]	)





   @property
   def 			snake_case	(							self:    Tuple	):
    if self.task == "image-classification":
     return OrderedDict([('logits', {0: 'batch'})]	)
    else:
     return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})]	)





   @property
   def 			snake_case	(							self:    Union[str, Any]	):
    return 1e-4



