




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


__A								=       logging.get_logger(__name__)

# General docstring
__A								=       "ResNetConfig"

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

# Image classification docstring
__A								=       "microsoft/resnet-50"
__A								=       "tiger cat"

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







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 3     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = "relu"				)       -> List[str]:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       nn.Convad(
							    lowerCamelCase__     ,		lowerCamelCase__     ,		kernel_size=lowerCamelCase__     ,		stride=lowerCamelCase__     ,		padding=kernel_size // 2     ,		bias=lowerCamelCase__				)
							__lowerCamelCase									=       nn.BatchNormad(lowerCamelCase__				)
							__lowerCamelCase									=       ACTaFN[activation] if activation is not None else nn.Identity()






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Tensor:



							'''simple docstring'''
							__lowerCamelCase									=       self.convolution(lowerCamelCase__				)
							__lowerCamelCase									=       self.normalization(lowerCamelCase__				)
							__lowerCamelCase									=       self.activation(lowerCamelCase__				)
							return hidden_state







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__				)       -> Dict:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       ResNetConvLayer(
							    config.num_channels     ,		config.embedding_size     ,		kernel_size=7     ,		stride=2     ,		activation=config.hidden_act				)
							__lowerCamelCase									=       nn.MaxPoolad(kernel_size=3     ,		stride=2     ,		padding=1				)
							__lowerCamelCase									=       config.num_channels






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Tensor:



							'''simple docstring'''
							__lowerCamelCase									=       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.'				)
							__lowerCamelCase									=       self.embedder(lowerCamelCase__				)
							__lowerCamelCase									=       self.pooler(lowerCamelCase__				)
							return embedding







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 2				)       -> Tuple:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       nn.Convad(lowerCamelCase__     ,		lowerCamelCase__     ,		kernel_size=1     ,		stride=lowerCamelCase__     ,		bias=lowerCamelCase__				)
							__lowerCamelCase									=       nn.BatchNormad(lowerCamelCase__				)






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Tensor:



							'''simple docstring'''
							__lowerCamelCase									=       self.convolution(lowerCamelCase__				)
							__lowerCamelCase									=       self.normalization(lowerCamelCase__				)
							return hidden_state







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = "relu"				)       -> Optional[int]:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       in_channels != out_channels or stride != 1
							__lowerCamelCase									=       (
							    ResNetShortCut(lowerCamelCase__     ,		lowerCamelCase__     ,		stride=lowerCamelCase__				) if should_apply_shortcut else nn.Identity()
							)
							__lowerCamelCase									=       nn.Sequential(
							    ResNetConvLayer(lowerCamelCase__     ,		lowerCamelCase__     ,		stride=lowerCamelCase__				)     ,		ResNetConvLayer(lowerCamelCase__     ,		lowerCamelCase__     ,		activation=lowerCamelCase__				)     ,		)
							__lowerCamelCase									=       ACTaFN[activation]






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> str:



							'''simple docstring'''
							__lowerCamelCase									=       hidden_state
							__lowerCamelCase									=       self.layer(lowerCamelCase__				)
							__lowerCamelCase									=       self.shortcut(lowerCamelCase__				)
							hidden_state += residual
							__lowerCamelCase									=       self.activation(lowerCamelCase__				)
							return hidden_state







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = "relu"     ,		lowerCamelCase__ = 4				)       -> List[str]:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       in_channels != out_channels or stride != 1
							__lowerCamelCase									=       out_channels // reduction
							__lowerCamelCase									=       (
							    ResNetShortCut(lowerCamelCase__     ,		lowerCamelCase__     ,		stride=lowerCamelCase__				) if should_apply_shortcut else nn.Identity()
							)
							__lowerCamelCase									=       nn.Sequential(
							    ResNetConvLayer(lowerCamelCase__     ,		lowerCamelCase__     ,		kernel_size=1				)     ,		ResNetConvLayer(lowerCamelCase__     ,		lowerCamelCase__     ,		stride=lowerCamelCase__				)     ,		ResNetConvLayer(lowerCamelCase__     ,		lowerCamelCase__     ,		kernel_size=1     ,		activation=lowerCamelCase__				)     ,		)
							__lowerCamelCase									=       ACTaFN[activation]






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Tuple:



							'''simple docstring'''
							__lowerCamelCase									=       hidden_state
							__lowerCamelCase									=       self.layer(lowerCamelCase__				)
							__lowerCamelCase									=       self.shortcut(lowerCamelCase__				)
							hidden_state += residual
							__lowerCamelCase									=       self.activation(lowerCamelCase__				)
							return hidden_state







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 2     ,		)       -> Any:



							'''simple docstring'''
							super().__init__()

							__lowerCamelCase									=       ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer

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






			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> Tensor:



							'''simple docstring'''
							__lowerCamelCase									=       input
							for layer in self.layers:
											__lowerCamelCase									=       layer(lowerCamelCase__				)
							return hidden_state







class        __lowerCAmelCase					(			nn.Module					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__				)       -> List[str]:



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






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = False     ,		lowerCamelCase__ = True				)       -> BaseModelOutputWithNoAttention:



							'''simple docstring'''
							__lowerCamelCase									=       () if output_hidden_states else None

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

											__lowerCamelCase									=       stage_module(lowerCamelCase__				)

							if output_hidden_states:
											__lowerCamelCase									=       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=lowerCamelCase__     ,		hidden_states=lowerCamelCase__     ,		)







class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			ResNetConfig
			snake_case_  						=			'''resnet'''
			snake_case_  						=			'''pixel_values'''
			snake_case_  						=			True


			def  lowercase_       ( self     ,		lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							if isinstance(lowerCamelCase__     ,		nn.Convad				):
											nn.init.kaiming_normal_(module.weight     ,		mode='fan_out'     ,		nonlinearity='relu'				)
							elif isinstance(lowerCamelCase__     ,		(nn.BatchNormad, nn.GroupNorm)				):
											nn.init.constant_(module.weight     ,		1				)
											nn.init.constant_(module.bias     ,		0				)






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__=False				)       -> int:



							'''simple docstring'''
							if isinstance(lowerCamelCase__     ,		lowerCamelCase__				):
											__lowerCamelCase									=       value




__A								=       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"

__A								=       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.'''     ,							__magic_name__     ,							)
class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__				)       -> Tuple:



							'''simple docstring'''
							super().__init__(lowerCamelCase__				)
							__lowerCamelCase									=       config
							__lowerCamelCase									=       ResNetEmbeddings(lowerCamelCase__				)
							__lowerCamelCase									=       ResNetEncoder(lowerCamelCase__				)
							__lowerCamelCase									=       nn.AdaptiveAvgPoolad((1, 1)				)
							# Initialize weights and apply final processing
							self.post_init()






			@add_start_docstrings_to_model_forward(lowerCamelCase__				)
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC     ,		output_type=lowerCamelCase__     ,		config_class=_CONFIG_FOR_DOC     ,		modality='vision'     ,		expected_output=_EXPECTED_OUTPUT_SHAPE     ,		)
			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None				)       -> BaseModelOutputWithPoolingAndNoAttention:



							'''simple docstring'''
							__lowerCamelCase									=       (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							__lowerCamelCase									=       return_dict if return_dict is not None else self.config.use_return_dict

							__lowerCamelCase									=       self.embedder(lowerCamelCase__				)

							__lowerCamelCase									=       self.encoder(
							    lowerCamelCase__     ,		output_hidden_states=lowerCamelCase__     ,		return_dict=lowerCamelCase__				)

							__lowerCamelCase									=       encoder_outputs[0]

							__lowerCamelCase									=       self.pooler(lowerCamelCase__				)

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

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







@add_start_docstrings(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''     ,							__magic_name__     ,							)
class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__				)       -> Union[str, Any]:



							'''simple docstring'''
							super().__init__(lowerCamelCase__				)
							__lowerCamelCase									=       config.num_labels
							__lowerCamelCase									=       ResNetModel(lowerCamelCase__				)
							# classification head
							__lowerCamelCase									=       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(lowerCamelCase__				)
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT     ,		output_type=lowerCamelCase__     ,		config_class=_CONFIG_FOR_DOC     ,		expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT     ,		)
			def  lowercase_       ( self     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None     ,		)       -> ImageClassifierOutputWithNoAttention:



							'''simple docstring'''
							__lowerCamelCase									=       return_dict if return_dict is not None else self.config.use_return_dict

							__lowerCamelCase									=       self.resnet(lowerCamelCase__     ,		output_hidden_states=lowerCamelCase__     ,		return_dict=lowerCamelCase__				)

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

							__lowerCamelCase									=       self.classifier(lowerCamelCase__				)

							__lowerCamelCase									=       None

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

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

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







@add_start_docstrings(
    '''
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    '''     ,							__magic_name__     ,							)
class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__					):

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__				)       -> Any:



							'''simple docstring'''
							super().__init__(lowerCamelCase__				)
							super()._init_backbone(lowerCamelCase__				)

							__lowerCamelCase									=       [config.embedding_size] + config.hidden_sizes
							__lowerCamelCase									=       ResNetEmbeddings(lowerCamelCase__				)
							__lowerCamelCase									=       ResNetEncoder(lowerCamelCase__				)

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






			@add_start_docstrings_to_model_forward(lowerCamelCase__				)
			@replace_return_docstrings(output_type=lowerCamelCase__     ,		config_class=_CONFIG_FOR_DOC				)
			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = None				)       -> BackboneOutput:



							'''simple docstring'''
							__lowerCamelCase									=       return_dict if return_dict is not None else self.config.use_return_dict
							__lowerCamelCase									=       (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)

							__lowerCamelCase									=       self.embedder(lowerCamelCase__				)

							__lowerCamelCase									=       self.encoder(lowerCamelCase__     ,		output_hidden_states=lowerCamelCase__     ,		return_dict=lowerCamelCase__				)

							__lowerCamelCase									=       outputs.hidden_states

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

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

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








from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block







@dataclass
class        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			snake_case_  						=			42







class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__					):

			"""simple docstring"""







			@register_to_config
			def __init__( self     ,		lowerCamelCase__ = 65_536     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 2     ,		lowerCamelCase__ = 0     ,		lowerCamelCase__ = "fourier"     ,		lowerCamelCase__ = True     ,		lowerCamelCase__ = False     ,		lowerCamelCase__ = 0.0     ,		lowerCamelCase__ = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")     ,		lowerCamelCase__ = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")     ,		lowerCamelCase__ = "UNetMidBlock1D"     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = (32, 32, 64)     ,		lowerCamelCase__ = None     ,		lowerCamelCase__ = 8     ,		lowerCamelCase__ = 1     ,		lowerCamelCase__ = False     ,		)       -> Dict:



							'''simple docstring'''
							super().__init__()
							__lowerCamelCase									=       sample_size

							# time
							if time_embedding_type == "fourier":
											__lowerCamelCase									=       GaussianFourierProjection(
											    embedding_size=8     ,		set_W_to_weight=lowerCamelCase__     ,		log=lowerCamelCase__     ,		flip_sin_to_cos=lowerCamelCase__				)
											__lowerCamelCase									=       2 * block_out_channels[0]
							elif time_embedding_type == "positional":
											__lowerCamelCase									=       Timesteps(
											    block_out_channels[0]     ,		flip_sin_to_cos=lowerCamelCase__     ,		downscale_freq_shift=lowerCamelCase__				)
											__lowerCamelCase									=       block_out_channels[0]

							if use_timestep_embedding:
											__lowerCamelCase									=       block_out_channels[0] * 4
											__lowerCamelCase									=       TimestepEmbedding(
											    in_channels=lowerCamelCase__     ,		time_embed_dim=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		out_dim=block_out_channels[0]     ,		)

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

							# down
							__lowerCamelCase									=       in_channels
							for i, down_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       block_out_channels[i]

											if i == 0:
															input_channel += extra_in_channels

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_down_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_downsample=not is_final_block or downsample_each_block     ,		)
											self.down_blocks.append(lowerCamelCase__				)

							# mid
							__lowerCamelCase									=       get_mid_block(
							    lowerCamelCase__     ,		in_channels=block_out_channels[-1]     ,		mid_channels=block_out_channels[-1]     ,		out_channels=block_out_channels[-1]     ,		embed_dim=block_out_channels[0]     ,		num_layers=lowerCamelCase__     ,		add_downsample=lowerCamelCase__     ,		)

							# up
							__lowerCamelCase									=       list(reversed(lowerCamelCase__				)				)
							__lowerCamelCase									=       reversed_block_out_channels[0]
							if out_block_type is None:
											__lowerCamelCase									=       out_channels
							else:
											__lowerCamelCase									=       block_out_channels[0]

							for i, up_block_type in enumerate(lowerCamelCase__				):
											__lowerCamelCase									=       output_channel
											__lowerCamelCase									=       (
											    reversed_block_out_channels[i + 1] if i < len(lowerCamelCase__				) - 1 else final_upsample_channels
											)

											__lowerCamelCase									=       i == len(lowerCamelCase__				) - 1

											__lowerCamelCase									=       get_up_block(
											    lowerCamelCase__     ,		num_layers=lowerCamelCase__     ,		in_channels=lowerCamelCase__     ,		out_channels=lowerCamelCase__     ,		temb_channels=block_out_channels[0]     ,		add_upsample=not is_final_block     ,		)
											self.up_blocks.append(lowerCamelCase__				)
											__lowerCamelCase									=       output_channel

							# out
							__lowerCamelCase									=       norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4     ,		32				)
							__lowerCamelCase									=       get_out_block(
							    out_block_type=lowerCamelCase__     ,		num_groups_out=lowerCamelCase__     ,		embed_dim=block_out_channels[0]     ,		out_channels=lowerCamelCase__     ,		act_fn=lowerCamelCase__     ,		fc_dim=block_out_channels[-1] // 4     ,		)






			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__ = True     ,		)       -> Union[UNetaDOutput, Tuple]:



							'''simple docstring'''
							__lowerCamelCase									=       timestep
							if not torch.is_tensor(lowerCamelCase__				):
											__lowerCamelCase									=       torch.tensor([timesteps]     ,		dtype=torch.long     ,		device=sample.device				)
							elif torch.is_tensor(lowerCamelCase__				) and len(timesteps.shape				) == 0:
											__lowerCamelCase									=       timesteps[None].to(sample.device				)

							__lowerCamelCase									=       self.time_proj(lowerCamelCase__				)
							if self.config.use_timestep_embedding:
											__lowerCamelCase									=       self.time_mlp(lowerCamelCase__				)
							else:
											__lowerCamelCase									=       timestep_embed[..., None]
											__lowerCamelCase									=       timestep_embed.repeat([1, 1, sample.shape[2]]				).to(sample.dtype				)
											__lowerCamelCase									=       timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])				)

							# 2. down
							__lowerCamelCase									=       ()
							for downsample_block in self.down_blocks:
											__lowerCamelCase			,		__lowerCamelCase									=       downsample_block(hidden_states=lowerCamelCase__     ,		temb=lowerCamelCase__				)
											down_block_res_samples += res_samples

							# 3. mid
							if self.mid_block:
											__lowerCamelCase									=       self.mid_block(lowerCamelCase__     ,		lowerCamelCase__				)

							# 4. up
							for i, upsample_block in enumerate(self.up_blocks				):
											__lowerCamelCase									=       down_block_res_samples[-1:]
											__lowerCamelCase									=       down_block_res_samples[:-1]
											__lowerCamelCase									=       upsample_block(lowerCamelCase__     ,		res_hidden_states_tuple=lowerCamelCase__     ,		temb=lowerCamelCase__				)

							# 5. post-process
							if self.out_block:
											__lowerCamelCase									=       self.out_block(lowerCamelCase__     ,		lowerCamelCase__				)

							if not return_dict:
											return (sample,)

							return UNetaDOutput(sample=lowerCamelCase__				)


