




from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block





@dataclass
class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 lowercase_							       =       42





class 			lowerCamelCase_				( nn.Module   ):


 '''simple docstring'''







 def __init__(				self    :						Dict							,							_lowerCAmelCase    :						Union[str, Any]=3							,							_lowerCAmelCase    :						Optional[int]=3							,							_lowerCAmelCase    :						Union[str, Any]=("DownEncoderBlock2D",)							,							_lowerCAmelCase    :						Any=(64,)							,							_lowerCAmelCase    :						Optional[int]=2							,							_lowerCAmelCase    :						Tuple=32							,							_lowerCAmelCase    :						Any="silu"							,							_lowerCAmelCase    :						Any=True							,							):
       super().__init__()
       SCREAMING_SNAKE_CASE_      		=     layers_per_block

       SCREAMING_SNAKE_CASE_      		=     torch.nn.Convad(
           _lowerCAmelCase							,							block_out_channels[0]							,							kernel_size=3							,							stride=1							,							padding=1							,							)

       SCREAMING_SNAKE_CASE_      		=     None
       SCREAMING_SNAKE_CASE_      		=     nn.ModuleList([]		)

       # down
       SCREAMING_SNAKE_CASE_      		=     block_out_channels[0]
       for i, down_block_type in enumerate(_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     output_channel
             SCREAMING_SNAKE_CASE_      		=     block_out_channels[i]
             SCREAMING_SNAKE_CASE_      		=     i == len(_lowerCAmelCase		) - 1

             SCREAMING_SNAKE_CASE_      		=     get_down_block(
                 _lowerCAmelCase							,							num_layers=self.layers_per_block							,							in_channels=_lowerCAmelCase							,							out_channels=_lowerCAmelCase							,							add_downsample=not is_final_block							,							resnet_eps=1E-6							,							downsample_padding=0							,							resnet_act_fn=_lowerCAmelCase							,							resnet_groups=_lowerCAmelCase							,							attention_head_dim=_lowerCAmelCase							,							temb_channels=_lowerCAmelCase							,							)
             self.down_blocks.append(_lowerCAmelCase		)

       # mid
       SCREAMING_SNAKE_CASE_      		=     UNetMidBlockaD(
           in_channels=block_out_channels[-1]							,							resnet_eps=1E-6							,							resnet_act_fn=_lowerCAmelCase							,							output_scale_factor=1							,							resnet_time_scale_shift='default'							,							attention_head_dim=block_out_channels[-1]							,							resnet_groups=_lowerCAmelCase							,							temb_channels=_lowerCAmelCase							,							)

       # out
       SCREAMING_SNAKE_CASE_      		=     nn.GroupNorm(num_channels=block_out_channels[-1]							,							num_groups=_lowerCAmelCase							,							eps=1E-6		)
       SCREAMING_SNAKE_CASE_      		=     nn.SiLU()

       SCREAMING_SNAKE_CASE_      		=     2 * out_channels if double_z else out_channels
       SCREAMING_SNAKE_CASE_      		=     nn.Convad(block_out_channels[-1]							,							_lowerCAmelCase							,							3							,							padding=1		)

       SCREAMING_SNAKE_CASE_      		=     False




 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						int		):
       SCREAMING_SNAKE_CASE_      		=     x
       SCREAMING_SNAKE_CASE_      		=     self.conv_in(_lowerCAmelCase		)

       if self.training and self.gradient_checkpointing:

             def create_custom_forward(_lowerCAmelCase    :						Dict		):
                   def custom_forward(*_lowerCAmelCase    :						Optional[Any]		):
                         return module(*_lowerCAmelCase		)

                   return custom_forward

             # down
             if is_torch_version('>='							,							'1.11.0'		):
                   for down_block in self.down_blocks:
                         SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(
                             create_custom_forward(_lowerCAmelCase		)							,							_lowerCAmelCase							,							use_reentrant=_lowerCAmelCase		)
                   # middle
                   SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(
                       create_custom_forward(self.mid_block		)							,							_lowerCAmelCase							,							use_reentrant=_lowerCAmelCase		)
             else:
                   for down_block in self.down_blocks:
                         SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCAmelCase		)							,							_lowerCAmelCase		)
                   # middle
                   SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block		)							,							_lowerCAmelCase		)

       else:
             # down
             for down_block in self.down_blocks:
                   SCREAMING_SNAKE_CASE_      		=     down_block(_lowerCAmelCase		)

             # middle
             SCREAMING_SNAKE_CASE_      		=     self.mid_block(_lowerCAmelCase		)

       # post-process
       SCREAMING_SNAKE_CASE_      		=     self.conv_norm_out(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.conv_act(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.conv_out(_lowerCAmelCase		)

       return sample





class 			lowerCamelCase_				( nn.Module   ):


 '''simple docstring'''







 def __init__(				self    :						Any							,							_lowerCAmelCase    :						str=3							,							_lowerCAmelCase    :						int=3							,							_lowerCAmelCase    :						List[Any]=("UpDecoderBlock2D",)							,							_lowerCAmelCase    :						List[str]=(64,)							,							_lowerCAmelCase    :						Optional[Any]=2							,							_lowerCAmelCase    :						Tuple=32							,							_lowerCAmelCase    :						int="silu"							,							_lowerCAmelCase    :						Any="group"							,							):
       super().__init__()
       SCREAMING_SNAKE_CASE_      		=     layers_per_block

       SCREAMING_SNAKE_CASE_      		=     nn.Convad(
           _lowerCAmelCase							,							block_out_channels[-1]							,							kernel_size=3							,							stride=1							,							padding=1							,							)

       SCREAMING_SNAKE_CASE_      		=     None
       SCREAMING_SNAKE_CASE_      		=     nn.ModuleList([]		)

       SCREAMING_SNAKE_CASE_      		=     in_channels if norm_type == 'spatial' else None

       # mid
       SCREAMING_SNAKE_CASE_      		=     UNetMidBlockaD(
           in_channels=block_out_channels[-1]							,							resnet_eps=1E-6							,							resnet_act_fn=_lowerCAmelCase							,							output_scale_factor=1							,							resnet_time_scale_shift='default' if norm_type == 'group' else norm_type							,							attention_head_dim=block_out_channels[-1]							,							resnet_groups=_lowerCAmelCase							,							temb_channels=_lowerCAmelCase							,							)

       # up
       SCREAMING_SNAKE_CASE_      		=     list(reversed(_lowerCAmelCase		)		)
       SCREAMING_SNAKE_CASE_      		=     reversed_block_out_channels[0]
       for i, up_block_type in enumerate(_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     output_channel
             SCREAMING_SNAKE_CASE_      		=     reversed_block_out_channels[i]

             SCREAMING_SNAKE_CASE_      		=     i == len(_lowerCAmelCase		) - 1

             SCREAMING_SNAKE_CASE_      		=     get_up_block(
                 _lowerCAmelCase							,							num_layers=self.layers_per_block + 1							,							in_channels=_lowerCAmelCase							,							out_channels=_lowerCAmelCase							,							prev_output_channel=_lowerCAmelCase							,							add_upsample=not is_final_block							,							resnet_eps=1E-6							,							resnet_act_fn=_lowerCAmelCase							,							resnet_groups=_lowerCAmelCase							,							attention_head_dim=_lowerCAmelCase							,							temb_channels=_lowerCAmelCase							,							resnet_time_scale_shift=_lowerCAmelCase							,							)
             self.up_blocks.append(_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     output_channel

       # out
       if norm_type == "spatial":
             SCREAMING_SNAKE_CASE_      		=     SpatialNorm(block_out_channels[0]							,							_lowerCAmelCase		)
       else:
             SCREAMING_SNAKE_CASE_      		=     nn.GroupNorm(num_channels=block_out_channels[0]							,							num_groups=_lowerCAmelCase							,							eps=1E-6		)
       SCREAMING_SNAKE_CASE_      		=     nn.SiLU()
       SCREAMING_SNAKE_CASE_      		=     nn.Convad(block_out_channels[0]							,							_lowerCAmelCase							,							3							,							padding=1		)

       SCREAMING_SNAKE_CASE_      		=     False




 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						List[Any]=None		):
       SCREAMING_SNAKE_CASE_      		=     z
       SCREAMING_SNAKE_CASE_      		=     self.conv_in(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     next(iter(self.up_blocks.parameters()		)		).dtype
       if self.training and self.gradient_checkpointing:

             def create_custom_forward(_lowerCAmelCase    :						Dict		):
                   def custom_forward(*_lowerCAmelCase    :						int		):
                         return module(*_lowerCAmelCase		)

                   return custom_forward

             if is_torch_version('>='							,							'1.11.0'		):
                   # middle
                   SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(
                       create_custom_forward(self.mid_block		)							,							_lowerCAmelCase							,							_lowerCAmelCase							,							use_reentrant=_lowerCAmelCase		)
                   SCREAMING_SNAKE_CASE_      		=     sample.to(_lowerCAmelCase		)

                   # up
                   for up_block in self.up_blocks:
                         SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(
                             create_custom_forward(_lowerCAmelCase		)							,							_lowerCAmelCase							,							_lowerCAmelCase							,							use_reentrant=_lowerCAmelCase		)
             else:
                   # middle
                   SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(
                       create_custom_forward(self.mid_block		)							,							_lowerCAmelCase							,							_lowerCAmelCase		)
                   SCREAMING_SNAKE_CASE_      		=     sample.to(_lowerCAmelCase		)

                   # up
                   for up_block in self.up_blocks:
                         SCREAMING_SNAKE_CASE_      		=     torch.utils.checkpoint.checkpoint(create_custom_forward(_lowerCAmelCase		)							,							_lowerCAmelCase							,							_lowerCAmelCase		)
       else:
             # middle
             SCREAMING_SNAKE_CASE_      		=     self.mid_block(_lowerCAmelCase							,							_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     sample.to(_lowerCAmelCase		)

             # up
             for up_block in self.up_blocks:
                   SCREAMING_SNAKE_CASE_      		=     up_block(_lowerCAmelCase							,							_lowerCAmelCase		)

        # post-process
       if latent_embeds is None:
             SCREAMING_SNAKE_CASE_      		=     self.conv_norm_out(_lowerCAmelCase		)
       else:
             SCREAMING_SNAKE_CASE_      		=     self.conv_norm_out(_lowerCAmelCase							,							_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.conv_act(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.conv_out(_lowerCAmelCase		)

       return sample





class 			lowerCamelCase_				( nn.Module   ):


 '''simple docstring'''







 def __init__(				self    :						str							,							_lowerCAmelCase    :						Optional[Any]							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						List[str]							,							_lowerCAmelCase    :						Optional[int]=None							,							_lowerCAmelCase    :						List[str]="random"							,							_lowerCAmelCase    :						Optional[int]=False							,							_lowerCAmelCase    :						Dict=True		):
       super().__init__()
       SCREAMING_SNAKE_CASE_      		=     n_e
       SCREAMING_SNAKE_CASE_      		=     vq_embed_dim
       SCREAMING_SNAKE_CASE_      		=     beta
       SCREAMING_SNAKE_CASE_      		=     legacy

       SCREAMING_SNAKE_CASE_      		=     nn.Embedding(self.n_e							,							self.vq_embed_dim		)
       self.embedding.weight.data.uniform_(-1.0 / self.n_e							,							1.0 / self.n_e		)

       SCREAMING_SNAKE_CASE_      		=     remap
       if self.remap is not None:
             self.register_buffer('used'							,							torch.tensor(np.load(self.remap		)		)		)
             SCREAMING_SNAKE_CASE_      		=     self.used.shape[0]
             SCREAMING_SNAKE_CASE_      		=     unknown_index  # "random" or "extra" or integer
             if self.unknown_index == "extra":
                   SCREAMING_SNAKE_CASE_      		=     self.re_embed
                   SCREAMING_SNAKE_CASE_      		=     self.re_embed + 1
             print(
                 F"Remapping {self.n_e} indices to {self.re_embed} indices. "
                 F"Using {self.unknown_index} for unknown indices."		)
       else:
             SCREAMING_SNAKE_CASE_      		=     n_e

       SCREAMING_SNAKE_CASE_      		=     sane_index_shape



 def  lowerCAmelCase_    (				self    :						Optional[int]							,							_lowerCAmelCase    :						Any		):
       SCREAMING_SNAKE_CASE_      		=     inds.shape
       assert len(_lowerCAmelCase		) > 1
       SCREAMING_SNAKE_CASE_      		=     inds.reshape(ishape[0]							,							-1		)
       SCREAMING_SNAKE_CASE_      		=     self.used.to(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     (inds[:, :, None] == used[None, None, ...]).long()
       SCREAMING_SNAKE_CASE_      		=     match.argmax(-1		)
       SCREAMING_SNAKE_CASE_      		=     match.sum(2		) < 1
       if self.unknown_index == "random":
             SCREAMING_SNAKE_CASE_      		=     torch.randint(0							,							self.re_embed							,							size=new[unknown].shape		).to(device=new.device		)
       else:
             SCREAMING_SNAKE_CASE_      		=     self.unknown_index
       return new.reshape(_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						int							,							_lowerCAmelCase    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     inds.shape
       assert len(_lowerCAmelCase		) > 1
       SCREAMING_SNAKE_CASE_      		=     inds.reshape(ishape[0]							,							-1		)
       SCREAMING_SNAKE_CASE_      		=     self.used.to(_lowerCAmelCase		)
       if self.re_embed > self.used.shape[0]:  # extra token
             SCREAMING_SNAKE_CASE_      		=     0  # simply set to zero
       SCREAMING_SNAKE_CASE_      		=     torch.gather(used[None, :][inds.shape[0] * [0], :]							,							1							,							_lowerCAmelCase		)
       return back.reshape(_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						Optional[int]		):
       # reshape z -> (batch, height, width, channel) and flatten
       SCREAMING_SNAKE_CASE_      		=     z.permute(0							,							2							,							3							,							1		).contiguous()
       SCREAMING_SNAKE_CASE_      		=     z.view(-1							,							self.vq_embed_dim		)

       # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
       SCREAMING_SNAKE_CASE_      		=     torch.argmin(torch.cdist(_lowerCAmelCase							,							self.embedding.weight		)							,							dim=1		)

       SCREAMING_SNAKE_CASE_      		=     self.embedding(_lowerCAmelCase		).view(z.shape		)
       SCREAMING_SNAKE_CASE_      		=     None
       SCREAMING_SNAKE_CASE_      		=     None

       # compute loss for embedding
       if not self.legacy:
             SCREAMING_SNAKE_CASE_      		=     self.beta * torch.mean((z_q.detach() - z) ** 2		) + torch.mean((z_q - z.detach()) ** 2		)
       else:
             SCREAMING_SNAKE_CASE_      		=     torch.mean((z_q.detach() - z) ** 2		) + self.beta * torch.mean((z_q - z.detach()) ** 2		)

       # preserve gradients
       SCREAMING_SNAKE_CASE_      		=     z + (z_q - z).detach()

       # reshape back to match original input shape
       SCREAMING_SNAKE_CASE_      		=     z_q.permute(0							,							3							,							1							,							2		).contiguous()

       if self.remap is not None:
             SCREAMING_SNAKE_CASE_      		=     min_encoding_indices.reshape(z.shape[0]							,							-1		)  # add batch axis
             SCREAMING_SNAKE_CASE_      		=     self.remap_to_used(_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     min_encoding_indices.reshape(-1							,							1		)  # flatten

       if self.sane_index_shape:
             SCREAMING_SNAKE_CASE_      		=     min_encoding_indices.reshape(z_q.shape[0]							,							z_q.shape[2]							,							z_q.shape[3]		)

       return z_q, loss, (perplexity, min_encodings, min_encoding_indices)




 def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						int		):
       # shape specifying (batch, height, width, channel)
       if self.remap is not None:
             SCREAMING_SNAKE_CASE_      		=     indices.reshape(shape[0]							,							-1		)  # add batch axis
             SCREAMING_SNAKE_CASE_      		=     self.unmap_to_all(_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     indices.reshape(-1		)  # flatten again

       # get quantized latent vectors
       SCREAMING_SNAKE_CASE_      		=     self.embedding(_lowerCAmelCase		)

       if shape is not None:
             SCREAMING_SNAKE_CASE_      		=     z_q.view(_lowerCAmelCase		)
             # reshape back to match original input shape
             SCREAMING_SNAKE_CASE_      		=     z_q.permute(0							,							3							,							1							,							2		).contiguous()

       return z_q





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 def __init__(				self    :						Union[str, Any]							,							_lowerCAmelCase    :						Tuple							,							_lowerCAmelCase    :						Dict=False		):
       SCREAMING_SNAKE_CASE_      		=     parameters
       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     torch.chunk(_lowerCAmelCase							,							2							,							dim=1		)
       SCREAMING_SNAKE_CASE_      		=     torch.clamp(self.logvar							,							-30.0							,							20.0		)
       SCREAMING_SNAKE_CASE_      		=     deterministic
       SCREAMING_SNAKE_CASE_      		=     torch.exp(0.5 * self.logvar		)
       SCREAMING_SNAKE_CASE_      		=     torch.exp(self.logvar		)
       if self.deterministic:
             SCREAMING_SNAKE_CASE_      		=     SCREAMING_SNAKE_CASE_      		=     torch.zeros_like(
                 self.mean							,							device=self.parameters.device							,							dtype=self.parameters.dtype		)



 def  lowerCAmelCase_    (				self    :						Optional[int]							,							_lowerCAmelCase    :						Optional[torch.Generator] = None		):
       # make sure sample is on the same device as the parameters and has same dtype
       SCREAMING_SNAKE_CASE_      		=     randn_tensor(
           self.mean.shape							,							generator=_lowerCAmelCase							,							device=self.parameters.device							,							dtype=self.parameters.dtype		)
       SCREAMING_SNAKE_CASE_      		=     self.mean + self.std * sample
       return x



 def  lowerCAmelCase_    (				self    :						List[str]							,							_lowerCAmelCase    :						Union[str, Any]=None		):
       if self.deterministic:
             return torch.Tensor([0.0]		)
       else:
             if other is None:
                   return 0.5 * torch.sum(torch.pow(self.mean							,							2		) + self.var - 1.0 - self.logvar							,							dim=[1, 2, 3]		)
             else:
                   return 0.5 * torch.sum(
                       torch.pow(self.mean - other.mean							,							2		) / other.var
                       + self.var / other.var
                       - 1.0
                       - self.logvar
                       + other.logvar							,							dim=[1, 2, 3]							,							)



 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Any							,							_lowerCAmelCase    :						Optional[int]=[1, 2, 3]		):
       if self.deterministic:
             return torch.Tensor([0.0]		)
       SCREAMING_SNAKE_CASE_      		=     np.log(2.0 * np.pi		)
       return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean							,							2		) / self.var							,							dim=_lowerCAmelCase		)




 def  lowerCAmelCase_    (				self    :						Tuple		):
       return self.mean

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