

import inspect
from typing import List, Optional, Tuple, Union

import torch

from ...models import UNetaDModel, VQModel
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput

class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										super().__init__()
										self.register_modules(vqvae=A_  ,   unet=A_  ,   scheduler=A_		)





						@torch.no_grad()
						def __call__(    self  ,   A_ = 1  ,   A_ = None  ,   A_ = 0.0  ,   A_ = 50  ,   A_ = "pil"  ,   A_ = True  ,   **A_  ,   ):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      randn_tensor(
										    (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size)  ,   generator=A_  ,   )
										_UpperCAmelCase    :						Union[str, Any]							=      latents.to(self.device		)

										# scale the initial noise by the standard deviation required by the scheduler
										_UpperCAmelCase    :						List[str]							=      latents * self.scheduler.init_noise_sigma

										self.scheduler.set_timesteps(A_		)

										# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
										_UpperCAmelCase    :						Dict							=      "eta" in set(inspect.signature(self.scheduler.step		).parameters.keys()		)

										_UpperCAmelCase    :						str							=      {}
										if accepts_eta:
														_UpperCAmelCase    :						Tuple							=      eta

										for t in self.progress_bar(self.scheduler.timesteps		):
														_UpperCAmelCase    :						Optional[Any]							=      self.scheduler.scale_model_input(A_  ,   A_		)
														# predict the noise residual
														_UpperCAmelCase    :						int							=      self.unet(A_  ,   A_		).sample
														# compute the previous noisy sample x_t -> x_t-1
														_UpperCAmelCase    :						Dict							=      self.scheduler.step(A_  ,   A_  ,   A_  ,   **A_		).prev_sample

										# decode the image latents with the VAE
										_UpperCAmelCase    :						List[Any]							=      self.vqvae.decode(A_		).sample

										_UpperCAmelCase    :						Tuple							=      (image / 2 + 0.5).clamp(0  ,   1		)
										_UpperCAmelCase    :						Any							=      image.cpu().permute(0  ,   2  ,   3  ,   1		).numpy()
										if output_type == "pil":
														_UpperCAmelCase    :						Any							=      self.numpy_to_pil(A_		)

										if not return_dict:
														return (image,)

										return ImagePipelineOutput(images=A_		)





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


SCREAMING_SNAKE_CASE_            = logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE_            = 'ResNetConfig'

# Base docstring
SCREAMING_SNAKE_CASE_            = 'microsoft/resnet-50'
SCREAMING_SNAKE_CASE_            = [1, 2048, 7, 7]

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

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

class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 3  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(
										    A_  ,   A_  ,   kernel_size=A_  ,   stride=A_  ,   padding=kernel_size // 2  ,   bias=A_		)
										_UpperCAmelCase    :						List[Any]							=      nn.BatchNormad(A_		)
										_UpperCAmelCase    :						Union[str, Any]							=      ACTaFN[activation] if activation is not None else nn.Identity()





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      self.convolution(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.normalization(A_		)
										_UpperCAmelCase    :						Optional[Any]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      ResNetConvLayer(
										    config.num_channels  ,   config.embedding_size  ,   kernel_size=7  ,   stride=2  ,   activation=config.hidden_act		)
										_UpperCAmelCase    :						List[str]							=      nn.MaxPoolad(kernel_size=3  ,   stride=2  ,   padding=1		)
										_UpperCAmelCase    :						List[Any]							=      config.num_channels





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						int							=      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."		)
										_UpperCAmelCase    :						int							=      self.embedder(A_		)
										_UpperCAmelCase    :						int							=      self.pooler(A_		)
										return embedding







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 2		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Union[str, Any]							=      nn.Convad(A_  ,   A_  ,   kernel_size=1  ,   stride=A_  ,   bias=A_		)
										_UpperCAmelCase    :						Optional[int]							=      nn.BatchNormad(A_		)





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      self.convolution(A_		)
										_UpperCAmelCase    :						List[str]							=      self.normalization(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[int]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Dict							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						int							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						Dict							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      hidden_state
										_UpperCAmelCase    :						Any							=      self.layer(A_		)
										_UpperCAmelCase    :						Optional[int]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Optional[int]							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_ = 1  ,   A_ = "relu"  ,   A_ = 4		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Optional[Any]							=      in_channels != out_channels or stride != 1
										_UpperCAmelCase    :						Optional[int]							=      out_channels // reduction
										_UpperCAmelCase    :						List[str]							=      (
										    ResNetShortCut(A_  ,   A_  ,   stride=A_		) if should_apply_shortcut else nn.Identity()
										)
										_UpperCAmelCase    :						Dict							=      nn.Sequential(
										    ResNetConvLayer(A_  ,   A_  ,   kernel_size=1		)  ,   ResNetConvLayer(A_  ,   A_  ,   stride=A_		)  ,   ResNetConvLayer(A_  ,   A_  ,   kernel_size=1  ,   activation=A_		)  ,   )
										_UpperCAmelCase    :						List[str]							=      ACTaFN[activation]





						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      hidden_state
										_UpperCAmelCase    :						List[str]							=      self.layer(A_		)
										_UpperCAmelCase    :						List[str]							=      self.shortcut(A_		)
										hidden_state += residual
										_UpperCAmelCase    :						Dict							=      self.activation(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_  ,   A_  ,   A_  ,   A_ = 2  ,   A_ = 2  ,   ):







										'''simple docstring'''


										super().__init__()

										_UpperCAmelCase    :						Any							=      ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

										_UpperCAmelCase    :						Optional[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_		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      input
										for layer in self.layers:
														_UpperCAmelCase    :						Optional[Any]							=      layer(A_		)
										return hidden_state







class 			a					(		nn.Module			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__()
										_UpperCAmelCase    :						Any							=      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]  ,   )		)
										_UpperCAmelCase    :						Union[str, Any]							=      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		):







										'''simple docstring'''


										_UpperCAmelCase    :						List[Any]							=      () if output_hidden_states else None

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

														_UpperCAmelCase    :						str							=      stage_module(A_		)

										if output_hidden_states:
														_UpperCAmelCase    :						int							=      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 			a					(		UpperCAmelCase			):
						_lowercase        =     ResNetConfig
						_lowercase        =     "resnet"
						_lowercase        =     "pixel_values"
						_lowercase        =     True


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										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		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		):
														_UpperCAmelCase    :						Optional[Any]							=      value







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

SCREAMING_SNAKE_CASE_            = 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  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						List[str]							=      config
										_UpperCAmelCase    :						Any							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						str							=      ResNetEncoder(A_		)
										_UpperCAmelCase    :						Any							=      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		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										_UpperCAmelCase    :						List[str]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						List[Any]							=      self.embedder(A_		)

										_UpperCAmelCase    :						str							=      self.encoder(
										    A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						List[Any]							=      encoder_outputs[0]

										_UpperCAmelCase    :						int							=      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    "							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase    :						Optional[int]							=      config.num_labels
										_UpperCAmelCase    :						str							=      ResNetModel(A_		)
										# classification head
										_UpperCAmelCase    :						int							=      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  ,   ):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      return_dict if return_dict is not None else self.config.use_return_dict

										_UpperCAmelCase    :						Tuple							=      self.resnet(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.pooler_output if return_dict else outputs[1]

										_UpperCAmelCase    :						int							=      self.classifier(A_		)

										_UpperCAmelCase    :						Dict							=      None

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

										if not return_dict:
														_UpperCAmelCase    :						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    "							,	UpperCAmelCase							,	)
class 			a					(		UpperCAmelCase							,	UpperCAmelCase			):


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										super().__init__(A_		)
										super()._init_backbone(A_		)

										_UpperCAmelCase    :						Optional[int]							=      [config.embedding_size] + config.hidden_sizes
										_UpperCAmelCase    :						str							=      ResNetEmbeddings(A_		)
										_UpperCAmelCase    :						List[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		):







										'''simple docstring'''


										_UpperCAmelCase    :						Tuple							=      return_dict if return_dict is not None else self.config.use_return_dict
										_UpperCAmelCase    :						Tuple							=      (
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)

										_UpperCAmelCase    :						Tuple							=      self.embedder(A_		)

										_UpperCAmelCase    :						Optional[int]							=      self.encoder(A_  ,   output_hidden_states=A_  ,   return_dict=A_		)

										_UpperCAmelCase    :						Optional[int]							=      outputs.hidden_states

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

										if not return_dict:
														_UpperCAmelCase    :						Union[str, 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_  ,   )


