"""simple docstring"""





from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


_UpperCamelCase     :		Optional[Any]											=					logging.get_logger(__name__)

# General docstring
_UpperCamelCase     :		Optional[int]											=					"ResNetConfig"

# Base docstring
_UpperCamelCase     :		List[str]											=					"microsoft/resnet-50"
_UpperCamelCase     :		Any											=					[1, 20_48, 7, 7]

# Image classification docstring
_UpperCamelCase     :		str											=					"microsoft/resnet-50"
_UpperCamelCase     :		Any											=					"tiger cat"

_UpperCamelCase     :		Any											=					[
    "microsoft/resnet-50",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]


class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a = 3	,    a = 1	,    a = "relu"							) ->      Tuple:
             super().__init__()
             lowercase__    :	List[Any]     					=			nn.Convad(
                 a	,    a	,    kernel_size=a	,    stride=a	,    padding=kernel_size // 2	,    bias=a							)
             lowercase__    :	List[str]     					=			nn.BatchNormad(a							)
             lowercase__    :	str     					=			ACTaFN[activation] if activation is not None else nn.Identity()


      def 	_UpperCAmelCase (     self	,    a							) ->      Tensor:
             lowercase__    :	Dict     					=			self.convolution(a							)
             lowercase__    :	Any     					=			self.normalization(a							)
             lowercase__    :	Any     					=			self.activation(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a							) ->      Tuple:
             super().__init__()
             lowercase__    :	List[Any]     					=			ResNetConvLayer(
                 config.num_channels	,    config.embedding_size	,    kernel_size=7	,    stride=2	,    activation=config.hidden_act							)
             lowercase__    :	Union[str, Any]     					=			nn.MaxPoolad(kernel_size=3	,    stride=2	,    padding=1							)
             lowercase__    :	Any     					=			config.num_channels


      def 	_UpperCAmelCase (     self	,    a							) ->      Tensor:
             lowercase__    :	Optional[Any]     					=			pixel_values.shape[1]
             if num_channels != self.num_channels:
                    raise ValueError(
                        'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'							)
             lowercase__    :	Dict     					=			self.embedder(a							)
             lowercase__    :	Dict     					=			self.pooler(a							)
             return embedding





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a = 2							) ->      List[str]:
             super().__init__()
             lowercase__    :	Union[str, Any]     					=			nn.Convad(a	,    a	,    kernel_size=1	,    stride=a	,    bias=a							)
             lowercase__    :	Union[str, Any]     					=			nn.BatchNormad(a							)


      def 	_UpperCAmelCase (     self	,    a							) ->      Tensor:
             lowercase__    :	Union[str, Any]     					=			self.convolution(a							)
             lowercase__    :	Optional[Any]     					=			self.normalization(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a = 1	,    a = "relu"							) ->      Dict:
             super().__init__()
             lowercase__    :	Optional[Any]     					=			in_channels != out_channels or stride != 1
             lowercase__    :	Union[str, Any]     					=			(
                 ResNetShortCut(a	,    a	,    stride=a							) if should_apply_shortcut else nn.Identity()
             )
             lowercase__    :	List[Any]     					=			nn.Sequential(
                 ResNetConvLayer(a	,    a	,    stride=a							)	,    ResNetConvLayer(a	,    a	,    activation=a							)	,    )
             lowercase__    :	Dict     					=			ACTaFN[activation]


      def 	_UpperCAmelCase (     self	,    a							) ->      List[Any]:
             lowercase__    :	List[str]     					=			hidden_state
             lowercase__    :	int     					=			self.layer(a							)
             lowercase__    :	Tuple     					=			self.shortcut(a							)
             hidden_state += residual
             lowercase__    :	Tuple     					=			self.activation(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a = 1	,    a = "relu"	,    a = 4							) ->      Any:
             super().__init__()
             lowercase__    :	List[Any]     					=			in_channels != out_channels or stride != 1
             lowercase__    :	int     					=			out_channels // reduction
             lowercase__    :	Tuple     					=			(
                 ResNetShortCut(a	,    a	,    stride=a							) if should_apply_shortcut else nn.Identity()
             )
             lowercase__    :	Any     					=			nn.Sequential(
                 ResNetConvLayer(a	,    a	,    kernel_size=1							)	,    ResNetConvLayer(a	,    a	,    stride=a							)	,    ResNetConvLayer(a	,    a	,    kernel_size=1	,    activation=a							)	,    )
             lowercase__    :	str     					=			ACTaFN[activation]


      def 	_UpperCAmelCase (     self	,    a							) ->      Any:
             lowercase__    :	Optional[int]     					=			hidden_state
             lowercase__    :	str     					=			self.layer(a							)
             lowercase__    :	List[Any]     					=			self.shortcut(a							)
             hidden_state += residual
             lowercase__    :	List[Any]     					=			self.activation(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a	,    a	,    a	,    a = 2	,    a = 2	,    ) ->      Union[str, Any]:
             super().__init__()

             lowercase__    :	Dict     					=			ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer

             lowercase__    :	List[Any]     					=			nn.Sequential(
                 # downsampling is done in the first layer with stride of 2
                 layer(a	,    a	,    stride=a	,    activation=config.hidden_act							)	,    *[layer(a	,    a	,    activation=config.hidden_act							) for _ in range(depth - 1							)]	,    )


      def 	_UpperCAmelCase (     self	,    a							) ->      Tensor:
             lowercase__    :	str     					=			input
             for layer in self.layers:
                    lowercase__    :	Tuple     					=			layer(a							)
             return hidden_state





class   UpperCAmelCase_			(					nn.Module):


      def __init__(     self	,    a							) ->      Optional[Any]:
             super().__init__()
             lowercase__    :	Tuple     					=			nn.ModuleList([]							)
             # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
             self.stages.append(
                 ResNetStage(
                     a	,    config.embedding_size	,    config.hidden_sizes[0]	,    stride=2 if config.downsample_in_first_stage else 1	,    depth=config.depths[0]	,    )							)
             lowercase__    :	Optional[int]     					=			zip(config.hidden_sizes	,    config.hidden_sizes[1:]							)
             for (in_channels, out_channels), depth in zip(a	,    config.depths[1:]							):
                    self.stages.append(ResNetStage(a	,    a	,    a	,    depth=a							)							)


      def 	_UpperCAmelCase (     self	,    a	,    a = False	,    a = True							) ->      BaseModelOutputWithNoAttention:
             lowercase__    :	Union[str, Any]     					=			() if output_hidden_states else None

             for stage_module in self.stages:
                    if output_hidden_states:
                           lowercase__    :	int     					=			hidden_states + (hidden_state,)

                    lowercase__    :	Optional[int]     					=			stage_module(a							)

             if output_hidden_states:
                    lowercase__    :	Tuple     					=			hidden_states + (hidden_state,)

             if not return_dict:
                    return tuple(v for v in [hidden_state, hidden_states] if v is not None							)

             return BaseModelOutputWithNoAttention(
                 last_hidden_state=a	,    hidden_states=a	,    )





class   UpperCAmelCase_			(					_a):
      lowerCamelCase__	:					Tuple										=						ResNetConfig
      lowerCamelCase__	:					Union[str, Any]										=						"resnet"
      lowerCamelCase__	:					int										=						"pixel_values"
      lowerCamelCase__	:					Any										=						True


      def 	_UpperCAmelCase (     self	,    a							) ->      Union[str, Any]:
             if isinstance(a	,    nn.Convad							):
                    nn.init.kaiming_normal_(module.weight	,    mode='fan_out'	,    nonlinearity='relu'							)
             elif isinstance(a	,    (nn.BatchNormad, nn.GroupNorm)							):
                    nn.init.constant_(module.weight	,    1							)
                    nn.init.constant_(module.bias	,    0							)


      def 	_UpperCAmelCase (     self	,    a	,    a=False							) ->      int:
             if isinstance(a	,    a							):
                    lowercase__    :	Any     					=			value





_UpperCamelCase     :		str											=					r"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

_UpperCamelCase     :		Tuple											=					r"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"


@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."				,							_a				,							)
class   UpperCAmelCase_			(					_a):


      def __init__(     self	,    a							) ->      List[Any]:
             super().__init__(a							)
             lowercase__    :	str     					=			config
             lowercase__    :	Dict     					=			ResNetEmbeddings(a							)
             lowercase__    :	Dict     					=			ResNetEncoder(a							)
             lowercase__    :	str     					=			nn.AdaptiveAvgPoolad((1, 1)							)
             # Initialize weights and apply final processing
             self.post_init()


      @add_start_docstrings_to_model_forward(a							)
      @add_code_sample_docstrings(
          checkpoint=_CHECKPOINT_FOR_DOC	,    output_type=a	,    config_class=_CONFIG_FOR_DOC	,    modality='vision'	,    expected_output=_EXPECTED_OUTPUT_SHAPE	,    )
      def 	_UpperCAmelCase (     self	,    a	,    a = None	,    a = None							) ->      BaseModelOutputWithPoolingAndNoAttention:
             lowercase__    :	List[Any]     					=			(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             lowercase__    :	Optional[int]     					=			return_dict if return_dict is not None else self.config.use_return_dict

             lowercase__    :	Tuple     					=			self.embedder(a							)

             lowercase__    :	int     					=			self.encoder(
                 a	,    output_hidden_states=a	,    return_dict=a							)

             lowercase__    :	Optional[int]     					=			encoder_outputs[0]

             lowercase__    :	Optional[Any]     					=			self.pooler(a							)

             if not return_dict:
                    return (last_hidden_state, pooled_output) + encoder_outputs[1:]

             return BaseModelOutputWithPoolingAndNoAttention(
                 last_hidden_state=a	,    pooler_output=a	,    hidden_states=encoder_outputs.hidden_states	,    )





@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "				,							_a				,							)
class   UpperCAmelCase_			(					_a):


      def __init__(     self	,    a							) ->      List[Any]:
             super().__init__(a							)
             lowercase__    :	Any     					=			config.num_labels
             lowercase__    :	Dict     					=			ResNetModel(a							)
             # classification head
             lowercase__    :	Optional[Any]     					=			nn.Sequential(
                 nn.Flatten()	,    nn.Linear(config.hidden_sizes[-1]	,    config.num_labels							) if config.num_labels > 0 else nn.Identity()	,    )
             # initialize weights and apply final processing
             self.post_init()


      @add_start_docstrings_to_model_forward(a							)
      @add_code_sample_docstrings(
          checkpoint=_IMAGE_CLASS_CHECKPOINT	,    output_type=a	,    config_class=_CONFIG_FOR_DOC	,    expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT	,    )
      def 	_UpperCAmelCase (     self	,    a = None	,    a = None	,    a = None	,    a = None	,    ) ->      ImageClassifierOutputWithNoAttention:
             lowercase__    :	Dict     					=			return_dict if return_dict is not None else self.config.use_return_dict

             lowercase__    :	Dict     					=			self.resnet(a	,    output_hidden_states=a	,    return_dict=a							)

             lowercase__    :	Union[str, Any]     					=			outputs.pooler_output if return_dict else outputs[1]

             lowercase__    :	Tuple     					=			self.classifier(a							)

             lowercase__    :	List[str]     					=			None

             if labels is not None:
                    if self.config.problem_type is None:
                           if self.num_labels == 1:
                                  lowercase__    :	List[Any]     					=			'regression'
                           elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                                  lowercase__    :	Union[str, Any]     					=			'single_label_classification'
                           else:
                                  lowercase__    :	Optional[int]     					=			'multi_label_classification'
                    if self.config.problem_type == "regression":
                           lowercase__    :	Any     					=			MSELoss()
                           if self.num_labels == 1:
                                  lowercase__    :	Any     					=			loss_fct(logits.squeeze()	,    labels.squeeze()							)
                           else:
                                  lowercase__    :	Dict     					=			loss_fct(a	,    a							)
                    elif self.config.problem_type == "single_label_classification":
                           lowercase__    :	List[str]     					=			CrossEntropyLoss()
                           lowercase__    :	List[str]     					=			loss_fct(logits.view(-1	,    self.num_labels							)	,    labels.view(-1							)							)
                    elif self.config.problem_type == "multi_label_classification":
                           lowercase__    :	Optional[int]     					=			BCEWithLogitsLoss()
                           lowercase__    :	List[str]     					=			loss_fct(a	,    a							)

             if not return_dict:
                    lowercase__    :	List[Any]     					=			(logits,) + outputs[2:]
                    return (loss,) + output if loss is not None else output

             return ImageClassifierOutputWithNoAttention(loss=a	,    logits=a	,    hidden_states=outputs.hidden_states							)





@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "				,							_a				,							)
class   UpperCAmelCase_			(					_a				,							_a):


      def __init__(     self	,    a							) ->      Any:
             super().__init__(a							)
             super()._init_backbone(a							)

             lowercase__    :	List[str]     					=			[config.embedding_size] + config.hidden_sizes
             lowercase__    :	Tuple     					=			ResNetEmbeddings(a							)
             lowercase__    :	Optional[Any]     					=			ResNetEncoder(a							)

             # initialize weights and apply final processing
             self.post_init()


      @add_start_docstrings_to_model_forward(a							)
      @replace_return_docstrings(output_type=a	,    config_class=_CONFIG_FOR_DOC							)
      def 	_UpperCAmelCase (     self	,    a	,    a = None	,    a = None							) ->      BackboneOutput:
             lowercase__    :	List[Any]     					=			return_dict if return_dict is not None else self.config.use_return_dict
             lowercase__    :	Optional[int]     					=			(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )

             lowercase__    :	List[str]     					=			self.embedder(a							)

             lowercase__    :	List[str]     					=			self.encoder(a	,    output_hidden_states=a	,    return_dict=a							)

             lowercase__    :	Union[str, Any]     					=			outputs.hidden_states

             lowercase__    :	Dict     					=			()
             for idx, stage in enumerate(self.stage_names							):
                    if stage in self.out_features:
                           feature_maps += (hidden_states[idx],)

             if not return_dict:
                    lowercase__    :	List[Any]     					=			(feature_maps,)
                    if output_hidden_states:
                           output += (outputs.hidden_states,)
                    return output

             return BackboneOutput(
                 feature_maps=a	,    hidden_states=outputs.hidden_states if output_hidden_states else None	,    attentions=a	,    )


"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import MobileViTImageProcessor


class   UpperCAmelCase_			(					unittest.TestCase):


      def __init__(     self	,    a	,    a=7	,    a=3	,    a=1_8	,    a=3_0	,    a=4_0_0	,    a=True	,    a=None	,    a=True	,    a=None	,    a=True	,    ) ->      List[str]:
             lowercase__    :	Tuple     					=			size if size is not None else {'shortest_edge': 2_0}
             lowercase__    :	Union[str, Any]     					=			crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}
             lowercase__    :	Optional[int]     					=			parent
             lowercase__    :	Optional[int]     					=			batch_size
             lowercase__    :	str     					=			num_channels
             lowercase__    :	Any     					=			image_size
             lowercase__    :	Optional[Any]     					=			min_resolution
             lowercase__    :	int     					=			max_resolution
             lowercase__    :	List[Any]     					=			do_resize
             lowercase__    :	List[str]     					=			size
             lowercase__    :	str     					=			do_center_crop
             lowercase__    :	List[Any]     					=			crop_size
             lowercase__    :	Union[str, Any]     					=			do_flip_channel_order


      def 	_UpperCAmelCase (     self							) ->      int:
             return {
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "do_center_crop": self.do_center_crop,
                 "crop_size": self.crop_size,
                 "do_flip_channel_order": self.do_flip_channel_order,
             }





@require_torch
@require_vision
class   UpperCAmelCase_			(					_a				,							unittest.TestCase):
      lowerCamelCase__	:					Optional[Any]										=						MobileViTImageProcessor if is_vision_available() else None


      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             lowercase__    :	Tuple     					=			MobileViTImageProcessingTester(self							)


      @property
      def 	_UpperCAmelCase (     self							) ->      int:
             return self.image_processor_tester.prepare_image_processor_dict()


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             lowercase__    :	List[str]     					=			self.image_processing_class(**self.image_processor_dict							)
             self.assertTrue(hasattr(a	,    'do_resize'							)							)
             self.assertTrue(hasattr(a	,    'size'							)							)
             self.assertTrue(hasattr(a	,    'do_center_crop'							)							)
             self.assertTrue(hasattr(a	,    'center_crop'							)							)
             self.assertTrue(hasattr(a	,    'do_flip_channel_order'							)							)


      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	Optional[int]     					=			self.image_processing_class.from_dict(self.image_processor_dict							)
             self.assertEqual(image_processor.size	,    {'shortest_edge': 2_0}							)
             self.assertEqual(image_processor.crop_size	,    {'height': 1_8, 'width': 1_8}							)

             lowercase__    :	str     					=			self.image_processing_class.from_dict(self.image_processor_dict	,    size=4_2	,    crop_size=8_4							)
             self.assertEqual(image_processor.size	,    {'shortest_edge': 4_2}							)
             self.assertEqual(image_processor.crop_size	,    {'height': 8_4, 'width': 8_4}							)


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             pass


      def 	_UpperCAmelCase (     self							) ->      str:
             # Initialize image_processing
             lowercase__    :	Any     					=			self.image_processing_class(**self.image_processor_dict							)
             # create random PIL images
             lowercase__    :	List[str]     					=			prepare_image_inputs(self.image_processor_tester	,    equal_resolution=a							)
             for image in image_inputs:
                    self.assertIsInstance(a	,    Image.Image							)

             # Test not batched input
             lowercase__    :	Union[str, Any]     					=			image_processing(image_inputs[0]	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )

             # Test batched
             lowercase__    :	List[Any]     					=			image_processing(a	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             # Initialize image_processing
             lowercase__    :	Dict     					=			self.image_processing_class(**self.image_processor_dict							)
             # create random numpy tensors
             lowercase__    :	Tuple     					=			prepare_image_inputs(self.image_processor_tester	,    equal_resolution=a	,    numpify=a							)
             for image in image_inputs:
                    self.assertIsInstance(a	,    np.ndarray							)

             # Test not batched input
             lowercase__    :	List[Any]     					=			image_processing(image_inputs[0]	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )

             # Test batched
             lowercase__    :	Any     					=			image_processing(a	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )


      def 	_UpperCAmelCase (     self							) ->      Dict:
             # Initialize image_processing
             lowercase__    :	str     					=			self.image_processing_class(**self.image_processor_dict							)
             # create random PyTorch tensors
             lowercase__    :	Optional[Any]     					=			prepare_image_inputs(self.image_processor_tester	,    equal_resolution=a	,    torchify=a							)
             for image in image_inputs:
                    self.assertIsInstance(a	,    torch.Tensor							)

             # Test not batched input
             lowercase__    :	Union[str, Any]     					=			image_processing(image_inputs[0]	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )

             # Test batched
             lowercase__    :	Tuple     					=			image_processing(a	,    return_tensors='pt'							).pixel_values
             self.assertEqual(
                 encoded_images.shape	,    (
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['height'],
                     self.image_processor_tester.crop_size['width'],
                 )	,    )

