



from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
							import PIL


SCREAMING_SNAKE_CASE__   			=   logging.get_logger(__name__)


def A    (							__UpperCamelCase			,						__UpperCamelCase       )    ->   List[Any]:
			A__	  =     b.T
			A__	  =     np.sum(np.square(__UpperCamelCase       )			,						axis=1       )
			A__	  =     np.sum(np.square(__UpperCamelCase       )			,						axis=0       )
			A__	  =     np.matmul(__UpperCamelCase			,						__UpperCamelCase       )
			A__	  =     aa[:, None] - 2 * ab + ba[None, :]
			return d


def A    (							__UpperCamelCase			,						__UpperCamelCase       )    ->   Optional[Any]:
			A__	  =     x.reshape(-1			,						3       )
			A__	  =     squared_euclidean_distance(__UpperCamelCase			,						__UpperCamelCase       )
			return np.argmin(__UpperCamelCase			,						axis=1       )






class   __lowerCAmelCase  (		UpperCAmelCase_   ):
					"""simple docstring"""






					A__					:		Dict      							=     ["pixel_values"]



					def __init__(  self       :							List[str]					,       _snake_case       :							Optional[Union[List[List[int]], np.ndarray]] = None					,       _snake_case       :							bool = True					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							PILImageResampling = PILImageResampling.BILINEAR					,       _snake_case       :							bool = True					,       _snake_case       :							bool = True					,       **_snake_case       :							Dict					,       ):






								"""simple docstring"""


								super().__init__(**_snake_case       )
								A__	  =     size if size is not None else {'height': 2_56, 'width': 2_56}
								A__	  =     get_size_dict(_snake_case       )
								A__	  =     np.array(_snake_case       ) if clusters is not None else None
								A__	  =     do_resize
								A__	  =     size
								A__	  =     resample
								A__	  =     do_normalize
								A__	  =     do_color_quantize



					def      _a				(  self       :							int					,       _snake_case       :							np.ndarray					,       _snake_case       :							Dict[str, int]					,       _snake_case       :							PILImageResampling = PILImageResampling.BILINEAR					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       **_snake_case       :							str					,       ):






								"""simple docstring"""


								A__	  =     get_size_dict(_snake_case       )
								if "height" not in size or "width" not in size:
											raise ValueError(F'''Size dictionary must contain both height and width keys. Got {size.keys()}'''       )
								return resize(
								    _snake_case					,       size=(size['height'], size['width'])					,       resample=_snake_case					,       data_format=_snake_case					,       **_snake_case       )



					def      _a				(  self       :							Any					,       _snake_case       :							np.ndarray					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = None					,       ):






								"""simple docstring"""


								A__	  =     rescale(image=_snake_case					,       scale=1 / 127.5					,       data_format=_snake_case       )
								A__	  =     image - 1
								return image



					def      _a				(  self       :							List[Any]					,       _snake_case       :							ImageInput					,       _snake_case       :							bool = None					,       _snake_case       :							Dict[str, int] = None					,       _snake_case       :							PILImageResampling = None					,       _snake_case       :							bool = None					,       _snake_case       :							Optional[bool] = None					,       _snake_case       :							Optional[Union[List[List[int]], np.ndarray]] = None					,       _snake_case       :							Optional[Union[str, TensorType]] = None					,       _snake_case       :							Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST					,       **_snake_case       :							int					,       ):






								"""simple docstring"""


								A__	  =     do_resize if do_resize is not None else self.do_resize
								A__	  =     size if size is not None else self.size
								A__	  =     get_size_dict(_snake_case       )
								A__	  =     resample if resample is not None else self.resample
								A__	  =     do_normalize if do_normalize is not None else self.do_normalize
								A__	  =     do_color_quantize if do_color_quantize is not None else self.do_color_quantize
								A__	  =     clusters if clusters is not None else self.clusters
								A__	  =     np.array(_snake_case       )

								A__	  =     make_list_of_images(_snake_case       )

								if not valid_images(_snake_case       ):
											raise ValueError(
											    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
											    'torch.Tensor, tf.Tensor or jax.ndarray.'       )

								if do_resize and size is None or resample is None:
											raise ValueError('Size and resample must be specified if do_resize is True.'       )

								if do_color_quantize and clusters is None:
											raise ValueError('Clusters must be specified if do_color_quantize is True.'       )

								# All transformations expect numpy arrays.
								A__	  =     [to_numpy_array(_snake_case       ) for image in images]

								if do_resize:
											A__	  =     [self.resize(image=_snake_case					,       size=_snake_case					,       resample=_snake_case       ) for image in images]

								if do_normalize:
											A__	  =     [self.normalize(image=_snake_case       ) for image in images]

								if do_color_quantize:
											A__	  =     [to_channel_dimension_format(_snake_case					,       ChannelDimension.LAST       ) for image in images]
											# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
											A__	  =     np.array(_snake_case       )
											A__	  =     color_quantize(_snake_case					,       _snake_case       ).reshape(images.shape[:-1]       )

											# flatten to (batch_size, height*width)
											A__	  =     images.shape[0]
											A__	  =     images.reshape(_snake_case					,       -1       )

											# We need to convert back to a list of images to keep consistent behaviour across processors.
											A__	  =     list(_snake_case       )
								else:
											A__	  =     [to_channel_dimension_format(_snake_case					,       _snake_case       ) for image in images]

								A__	  =     {'input_ids': images}
								return BatchFeature(data=_snake_case					,       tensor_type=_snake_case       )






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


lowercase__											=logging.get_logger(__name__)

# General docstring
lowercase__											='ResNetConfig'

# Base docstring
lowercase__											='microsoft/resnet-50'
lowercase__											=[1, 20_48, 7, 7]

# Image classification docstring
lowercase__											='microsoft/resnet-50'
lowercase__											='tiger cat'

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







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 3					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"	):
				super().__init__()
				a_      				=						nn.Convad(
				    UpperCAmelCase					,   UpperCAmelCase					,   kernel_size=UpperCAmelCase					,   stride=UpperCAmelCase					,   padding=kernel_size // 2					,   bias=UpperCAmelCase	)
				a_      				=						nn.BatchNormad(UpperCAmelCase	)
				a_      				=						ACTaFN[activation] if activation is not None else nn.Identity()






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						self.convolution(UpperCAmelCase	)
				a_      				=						self.normalization(UpperCAmelCase	)
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase	):
				super().__init__()
				a_      				=						ResNetConvLayer(
				    config.num_channels					,   config.embedding_size					,   kernel_size=7					,   stride=2					,   activation=config.hidden_act	)
				a_      				=						nn.MaxPoolad(kernel_size=3					,   stride=2					,   padding=1	)
				a_      				=						config.num_channels






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						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."""	)
				a_      				=						self.embedder(UpperCAmelCase	)
				a_      				=						self.pooler(UpperCAmelCase	)
				return embedding







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 2	):
				super().__init__()
				a_      				=						nn.Convad(UpperCAmelCase					,   UpperCAmelCase					,   kernel_size=1					,   stride=UpperCAmelCase					,   bias=UpperCAmelCase	)
				a_      				=						nn.BatchNormad(UpperCAmelCase	)






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						self.convolution(UpperCAmelCase	)
				a_      				=						self.normalization(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"	):
				super().__init__()
				a_      				=						in_channels != out_channels or stride != 1
				a_      				=						(
				    ResNetShortCut(UpperCAmelCase					,   UpperCAmelCase					,   stride=UpperCAmelCase	) if should_apply_shortcut else nn.Identity()
				)
				a_      				=						nn.Sequential(
				    ResNetConvLayer(UpperCAmelCase					,   UpperCAmelCase					,   stride=UpperCAmelCase	)					,   ResNetConvLayer(UpperCAmelCase					,   UpperCAmelCase					,   activation=UpperCAmelCase	)					,   )
				a_      				=						ACTaFN[activation]






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						hidden_state
				a_      				=						self.layer(UpperCAmelCase	)
				a_      				=						self.shortcut(UpperCAmelCase	)
				hidden_state += residual
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"					,   UpperCAmelCase = 4	):
				super().__init__()
				a_      				=						in_channels != out_channels or stride != 1
				a_      				=						out_channels // reduction
				a_      				=						(
				    ResNetShortCut(UpperCAmelCase					,   UpperCAmelCase					,   stride=UpperCAmelCase	) if should_apply_shortcut else nn.Identity()
				)
				a_      				=						nn.Sequential(
				    ResNetConvLayer(UpperCAmelCase					,   UpperCAmelCase					,   kernel_size=1	)					,   ResNetConvLayer(UpperCAmelCase					,   UpperCAmelCase					,   stride=UpperCAmelCase	)					,   ResNetConvLayer(UpperCAmelCase					,   UpperCAmelCase					,   kernel_size=1					,   activation=UpperCAmelCase	)					,   )
				a_      				=						ACTaFN[activation]






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						hidden_state
				a_      				=						self.layer(UpperCAmelCase	)
				a_      				=						self.shortcut(UpperCAmelCase	)
				hidden_state += residual
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 2					,   UpperCAmelCase = 2					,   ):
				super().__init__()

				a_      				=						ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer

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






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						input
				for layer in self.layers:
					a_      				=						layer(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase	):
				super().__init__()
				a_      				=						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(
				        UpperCAmelCase					,   config.embedding_size					,   config.hidden_sizes[0]					,   stride=2 if config.downsample_in_first_stage else 1					,   depth=config.depths[0]					,   )	)
				a_      				=						zip(config.hidden_sizes					,   config.hidden_sizes[1:]	)
				for (in_channels, out_channels), depth in zip(UpperCAmelCase					,   config.depths[1:]	):
					self.stages.append(ResNetStage(UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase					,   depth=UpperCAmelCase	)	)






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = False					,   UpperCAmelCase = True	):
				a_      				=						() if output_hidden_states else None

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

					a_      				=						stage_module(UpperCAmelCase	)

				if output_hidden_states:
					a_      				=						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=UpperCAmelCase					,   hidden_states=UpperCAmelCase					,   )







class   a_ (      UpperCamelCase__					):
			lowerCamelCase__	:			List[Any]       =    ResNetConfig
			lowerCamelCase__	:			Dict       =    'resnet'
			lowerCamelCase__	:			Dict       =    'pixel_values'
			lowerCamelCase__	:			str       =    True




			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				if isinstance(UpperCAmelCase					,   nn.Convad	):
					nn.init.kaiming_normal_(module.weight					,   mode="""fan_out"""					,   nonlinearity="""relu"""	)
				elif isinstance(UpperCAmelCase					,   (nn.BatchNormad, nn.GroupNorm)	):
					nn.init.constant_(module.weight					,   1	)
					nn.init.constant_(module.bias					,   0	)






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase=False	):
				if isinstance(UpperCAmelCase					,   UpperCAmelCase	):
					a_      				=						value







lowercase__											=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'

lowercase__											=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.'		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				super().__init__(UpperCAmelCase	)
				a_      				=						config
				a_      				=						ResNetEmbeddings(UpperCAmelCase	)
				a_      				=						ResNetEncoder(UpperCAmelCase	)
				a_      				=						nn.AdaptiveAvgPoolad((1, 1)	)
				# Initialize weights and apply final processing
				self.post_init()






			@add_start_docstrings_to_model_forward(UpperCAmelCase	)
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC					,   output_type=UpperCAmelCase					,   config_class=_CONFIG_FOR_DOC					,   modality="""vision"""					,   expected_output=_EXPECTED_OUTPUT_SHAPE					,   )
			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = None					,   UpperCAmelCase = None	):
				a_      				=						(
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				a_      				=						return_dict if return_dict is not None else self.config.use_return_dict

				a_      				=						self.embedder(UpperCAmelCase	)

				a_      				=						self.encoder(
				    UpperCAmelCase					,   output_hidden_states=UpperCAmelCase					,   return_dict=UpperCAmelCase	)

				a_      				=						encoder_outputs[0]

				a_      				=						self.pooler(UpperCAmelCase	)

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

				return BaseModelOutputWithPoolingAndNoAttention(
				    last_hidden_state=UpperCAmelCase					,   pooler_output=UpperCAmelCase					,   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    '		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				super().__init__(UpperCAmelCase	)
				a_      				=						config.num_labels
				a_      				=						ResNetModel(UpperCAmelCase	)
				# classification head
				a_      				=						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(UpperCAmelCase	)
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT					,   output_type=UpperCAmelCase					,   config_class=_CONFIG_FOR_DOC					,   expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT					,   )
			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   ):
				a_      				=						return_dict if return_dict is not None else self.config.use_return_dict

				a_      				=						self.resnet(UpperCAmelCase					,   output_hidden_states=UpperCAmelCase					,   return_dict=UpperCAmelCase	)

				a_      				=						outputs.pooler_output if return_dict else outputs[1]

				a_      				=						self.classifier(UpperCAmelCase	)

				a_      				=						None

				if labels is not None:
					if self.config.problem_type is None:
						if self.num_labels == 1:
							a_      				=						"""regression"""
						elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
							a_      				=						"""single_label_classification"""
						else:
							a_      				=						"""multi_label_classification"""
					if self.config.problem_type == "regression":
						a_      				=						MSELoss()
						if self.num_labels == 1:
							a_      				=						loss_fct(logits.squeeze()					,   labels.squeeze()	)
						else:
							a_      				=						loss_fct(UpperCAmelCase					,   UpperCAmelCase	)
					elif self.config.problem_type == "single_label_classification":
						a_      				=						CrossEntropyLoss()
						a_      				=						loss_fct(logits.view(-1					,   self.num_labels	)					,   labels.view(-1	)	)
					elif self.config.problem_type == "multi_label_classification":
						a_      				=						BCEWithLogitsLoss()
						a_      				=						loss_fct(UpperCAmelCase					,   UpperCAmelCase	)

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

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







@add_start_docstrings(
    '\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    '		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__		,  UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				super().__init__(UpperCAmelCase	)
				super()._init_backbone(UpperCAmelCase	)

				a_      				=						[config.embedding_size] + config.hidden_sizes
				a_      				=						ResNetEmbeddings(UpperCAmelCase	)
				a_      				=						ResNetEncoder(UpperCAmelCase	)

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






			@add_start_docstrings_to_model_forward(UpperCAmelCase	)
			@replace_return_docstrings(output_type=UpperCAmelCase					,   config_class=_CONFIG_FOR_DOC	)
			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = None					,   UpperCAmelCase = None	):
				a_      				=						return_dict if return_dict is not None else self.config.use_return_dict
				a_      				=						(
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)

				a_      				=						self.embedder(UpperCAmelCase	)

				a_      				=						self.encoder(UpperCAmelCase					,   output_hidden_states=UpperCAmelCase					,   return_dict=UpperCAmelCase	)

				a_      				=						outputs.hidden_states

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

				if not return_dict:
					a_      				=						(feature_maps,)
					if output_hidden_states:
						output += (outputs.hidden_states,)
					return output

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